Search code examples
iosswiftuitextfielduipickerview

Get UITextField from UIPickerView when using it as input view


Is there a possibility to get UITextField from UIPickerView? I set my UIPickerView as inputView for text filed. I have few text fields on the screen and I want to simple get current text field that shown picker view.

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
   // something like let textField = pickerView.requestedTextField
}

Is there any way to do it?


Solution

  • If you have multiple textField that show pickerView then create one more instance of textField in your viewController like this and use this object inside textFieldDidBeginEditing and assign the reference of that textField to that tempTextField.

    var selectedTextField: UITextField = UITextField()
    
    func textFieldDidBeginEditing(textField: UITextField!) { 
        self.selectedTextField = textField
    }
    

    Now in didSelectRow method of PickerView use this textField o know the current editing field.

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if self.selectedTextField == countryField {
            //Set text for countryField 
        }
        else self.selectedTextField == stateField {
            //Set text for stateField 
        }
    }
    

    Note: For example I have used countryField and stateField you can use textField for that you want to set text.