问题是“Eye Button”只应在选择了文本字段时显示。我用“isFirstResponder”试过了,但似乎没用。你知道怎么处理吗?在下面的图片中,没有选择文本字段。
更新
委托函数“password did change”工作正常。我唯一需要的是,如果不再选择文本字段,按钮应该隐藏。添加委托函数“beging”或“endEditing”不起作用。这只会导致另一个失败,如果用户输入了一些内容,取消选择文本字段并再次选择它,文本将被删除。
@IBAction func passwordDidChange(_ sender: Any) {
if self.passwordTextField.text == "" && self.passwordTextField.isFirstResponder != true{
self.eyeOpenButton.isHidden = true
}else {
self.eyeOpenButton.isHidden = false
}
最佳答案
你可以试试这样的。
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.eyeOpenButton.isHidden = true
passwordTextField.delegate = self
}
// calls when textfield becomes 1st responder
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
switch textField {
case passwordTextField:
if passwordTextField.text != "" {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
} else {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
}
break
default:
break
}
return true
}
//Calls when the text fields resigns first responder
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if textField == passwordTextField {
if passwordTextField.text != "" {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
} else {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
}
}
return true
}
// Check all the input user has with the keyboard.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let passwordTextField = passwordTextField {
if passwordTextField.text?.count ?? 0 > 0 {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
}
if passwordTextField.text?.count == 0 {
self.eyeOpenButton.isHidden = !self.eyeOpenButton.isHidden
}
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
for textField in self.view.subviews where textField is UITextField {
textField.resignFirstResponder()
}
return true
}
}
关于ios - 检查UITextfield是否处于事件状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57853455/