How to determine which textfield is active swift

前端 未结 7 1734
太阳男子
太阳男子 2020-12-06 04:01

I cant figure out which UITextField is currently active so i can clear its text if they hit cancel on a UIBarButtonItem. Here is my code. There is

7条回答
  •  情书的邮戳
    2020-12-06 04:45

    You can declare a UITextField property in your class, and assign the current text field to it in textFieldDidBeginEditing. Then you can just call this text field whenever you need to.

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

提交回复
热议问题