Search code examples
iosswiftuistepper

How to update UIStepper value if we change the text from UITextField?


I want to allow the user to input their weight by typing their weight but also tap +/- using a stepper.

It works fine if they only use one of the ways. They can use the stepper and the value will add up. But if they change the text manually then use stepper again, the value won't change according to the text. Instead it follows the stepper value.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var txtWeight: UITextField!
    @IBOutlet weak var stpWeight: UIStepper!

    @IBAction func stpActWeight(_ sender: Any) {
        txtWeight.text = "\(stpWeight.value)"
    }
}

I expect if I change the txtWeight.txt to 50.0 then press + from the stepper then it will be 51.0. Currently the actual output is the stepper value (if I click + 3 times, then the stepper value is 3.0).


Solution

  • You can try

    // add these in viewDidLoad 
    txtWeight.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    

    and

    func textFieldDidChange(_ textField: UITextField) {
       self.stpWeight.value = Double(textField.text!) ?? 0.0 
    } 
    @IBAction func stpActWeight(_ sender: Any) {
        txtWeight.text = "\(stpWeight.value)" 
    }