简体   繁体   中英

UIPickerView as an inputView of multiple UITextFields

I have three UITextField s in my code and single UIPickerView as in inputView of all text fields.

I want to identify, which text field has invoked/opened UIPickerView, inside the UIPickerViewDelegate method pickerView(_:didSelectRow:inComponent:) .

Here is sample code I've tried:

let tf1: UITextField()
let tf2: UITextField()
let tf3: UITextField()
let pcv: UIPickerView()


tf1.inputView = pcv
tf2.inputView = pcv
tf3.inputView = pcv


// Picker view delegate
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if (tf1.isFirstResponder) {
       print("tf1")
    } else if (tf2.isFirstResponder) {
       print("tf2")
    } else if (tf3.isFirstResponder) {
       print("tf3")
    } else {
       print("Any other view")
    }

}

Is there any other better way to handle this?

(Objective C or Swift, any solution)

on your textfield delegate assign the inputview and tag for your textfield

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   textField.inputView = pcv
   pcv.tag =  textField.tag
    return true;
}

and finally get the tag for pickerview for identify which textfield you tapped.

 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("pickerView == \(pickerView.tag)")

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM