Search code examples
iosswiftuitextfielduipickerviewuialertcontroller

How can I update text on alert controller's UITextField from the pickerView didSelectRow delegate method?


I want to update a UITextField inside a UIAlertController when my UIPickerView scrolls.

I tried to add a tag on my textfield:

myTextField.addTextField(configurationHandler: { (textField) -> Void in
        textField.inputView = self.myPickerView
        textField.tag = 2
        textField.delegate = self
})

For the pickerView delegate method didSelectRow I declared a ivar pickerViewName to store the row's name:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    pickerViewName = myArray[row].name
    //Update UITextField text here, but unable to get it's tag.
}

and on the textFieldDidBeginEditing delegate method:

func textFieldDidBeginEditing(_ textField: UITextField) {

    if (textField.tag == 2)
    {
        textField.text = pickerViewName!
    }

}

It isn't working however. When I scrolled up and down the textfield does not update. Much appreciated if you could help me point out where my mistake is! Thank you.


Solution

  • In your code you are doing following: if the picker scrolls you assign a new name to the variable. However you never call update for the textfield. Your name is assigned after you start editing text field. I am not sure if this is desired, otherwise you will have to call it manually.