我在视图中有多个textFields,其中输入视图设置为pickerView,但是根据textField,应该出现不同数量的选择行。当您在选择器视图外部单击,然后单击下一个textField时,此方法工作正常,但是当您仅单击下一个textField时,会导致崩溃(这是因为pickerView不会更改,因此索引超出范围)。谢谢您的帮助!
若要在每次在外部轻按时关闭pickerView(如果轻按另一个textField则不执行任何操作):
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
当我说不同的textFields显示不同数量的行时,我的意思是:
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if ticketOneTextField.isFirstResponder == true {
if shownEvent?.ticketTypeOnePrice == "0.00" {
return 2
} else {
return 11
}
} else if ticketTwoTextField.isFirstResponder == true {
if shownEvent?.ticketTypeTwoPrice == "0.00" {
return 2
} else {
return 11
}
} else if ticketThreeTextField.isFirstResponder == true {
if shownEvent?.ticketTypeThreePrice == "0.00" {
return 2
} else {
return 11
}
} else {
return 2
}
}
最佳答案
添加到viewDidLoad()
当用户开始编辑以下功能时,将调用该功能。
textField.addTarget(self, action:#selector(textDidBeginEditing(_:)), forControlEvents: UIControlEvents.EditingDidBegin)
然后实现:
func textDidBeginEditing(sender:UITextField) -> Void
{
if sender == ticketOneTextField {
//show pickerview
}
else if sender == ticketOneTextField {
//show pickerview
}
else if sender == ticketOneTextField {
//show pickerview
}
}
// this pickerview delegate is called when user selects a row.
optional func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//after user selects the value end the editing
self.view.endEditing(true)
}