我无法弄清楚哪个UITextField当前处于活动状态,因此如果它们在上单击“取消”,则可以清除其文本UIBarButtonItem。这是我的代码。有一个视图UIPickerView,UIToolBar和两个栏按钮的项目。取消项的操作只能清除其文本,我无法弄清楚如何获得正确的文本UITextField。
UITextField
UIBarButtonItem
UIPickerView
UIToolBar
我都尝试过这两个:
@IBAction func cancelText(sender: AnyObject) { if self.truckYear.editing == true{ println("truckYear") clearText(self.truckYear) } else if self.truckMake.editing == true{ clearText(self.truckMake) } } @IBAction func doneText(sender: AnyObject) { pickerView.hidden = true } func clearText(textField:UITextField){ println("in clear text") textField.text = nil }
和:
@IBAction func cancelText(sender: AnyObject) { if self.truckYear.isFirstResponder(){ println("truckYear") clearText(self.truckYear) } else if self.truckMake.isFirstResponder(){ clearText(self.truckMake) } } @IBAction func doneText(sender: AnyObject) { pickerView.hidden = true } func clearText(textField:UITextField){ println("in clear text") textField.text = nil }
您可以UITextField在类中声明一个属性,然后在中为它分配当前文本字段textFieldDidBeginEditing。然后,您可以在需要时随时调用此文本字段。
textFieldDidBeginEditing
class ViewController : UIViewController, UITextFieldDelegate { var activeTextField = UITextField() // Assign the newly active text field to your activeTextField variable func textFieldDidBeginEditing(textField: UITextField) { self.activeTextField = textField } // Call activeTextField whenever you need to func anotherMethod() { // self.activeTextField.text is an optional, we safely unwrap it here if let activeTextFieldText = self.activeTextField.text { print("Active text field's text: \(activeTextFieldText)") return; } print("Active text field is empty") } }