Search code examples
iosswiftuitextfielduipickerview

onTextChange target not called when text is changed with picker view - iOS Swift


I have two text fields.

One is for person type: "Husband, "Wife", "Single", "Child". The other is for birth order.

I want the birth order text field to be enabled only when the text of the person type text field is "Child".

The input view of the person type text field is a picker view with the 4 options. I've tried adding a target to my person type text field like so:

personTypeTextField.addTarget(self, action: #selector(onTextChange), for: UIControlEvents.editingChanged)

Then the onTextChange function does this:

func onTextChange() {
    if personTypeTextField.text == "Child" {
        birthOrderTextField.isEnabled = true
    } else {
        birthOrderTextField.isEnabled = false
        birthOrderTextField.text = ""
    }
}

But the onTextChange function isn't called when I make a person type selection with the picker view. Why isn't it called?


Solution

  • You can use below UIPickerView delgate method Instead of textField selector

    Responding to Row Selection

    func pickerView(UIPickerView,didSelectRow: Int, inComponent: Int)

    Called by the picker view when the user selects a row in a component.

    self.personTypeTextField.text = YOUR_ARRAY[row]
    

    Finally check

    if personTypeTextField.text == "Child" {
            birthOrderTextField.isEnabled = true
        } else {
            birthOrderTextField.isEnabled = false
            birthOrderTextField.text = ""
        }
    

    Don't forget to assign delegate to pickerView.