UIPickerView作为多个UITextField的inputView

时间:2019-02-08 10:15:08

标签: ios objective-c swift uitextfield uipickerview

我的代码中有3个UITextField,所有文本字段中的UIPickerView也有一个inputView

我想在UIPickerViewDelegate方法pickerView(_:didSelectRow:inComponent:)中识别出哪个文本字段已调用/打开了UIPickerView。

这是我尝试过的示例代码:

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")
    }

}

还有其他更好的方法来解决这个问题吗?

(目标C或Swift,任何解决方案)

1 个答案:

答案 0 :(得分:1)

在您的文本字段委托中,为文本字段分配inputview和标签

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

并最终获得pickerview的标签,以识别您点击了哪个文本字段。

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

}