Search code examples
swiftliveself-updating

Swift - Automatically updating textfields


I am wanting to take these textfields and preform an equation between them. What I am having trouble with is automatically updating the final textfield after my equation is done

In this scenario, I want the Total Cash Price to be updated when the Vehicle Price is updated or the Service Contract is updated without having to press the DP Button.

Can someone give me a suggestion on how to accomplish this.

Code:

@IBAction func DPButtonPressed(_ sender: Any) {
        totalCashPrice.integerValue = vehiclePrice.integerValue + serviceContract.integerValue + salesTax.integerValue
}

Instead of it being @IBOutlet func DPButtonPressed(_sender: Any), i want that function to be automatically done.

enter image description here

This is where i am stuck at with using the delegate

 override func viewDidLoad() {
    super.viewDidLoad()
    totalCashPrice.delegate = self

}
func textFieldDidBeginEditing(textField: NSTextField!) {

}
func textFieldShouldEndEditing(textField: NSTextField!) -> Bool {
    return false
}
func textFieldShouldReturn(textField: NSTextField!) -> Bool {
    totalCashPrice.resignFirstResponder()
    return true
}

@IBAction func DPButtonPressed(_ sender: Any) {
    totalCashPrice.integerValue = vehiclePrice.integerValue + 
serviceContract.integerValue + salesTax.integerValue
    textFieldShouldEndEditing(textField: totalCashPrice)

enter image description here


Solution

  • Cocoa is event driven. Pick an event and let it drive you.

    You just need to decide what kind of signal you want to respond to and configure things so that you get that signal. It’s simply a matter of specifying to yourself what “when the Vehicle Price is updated or the Service Contract is updated” means, ie what sort of user action counts as updating the field.