问题是仅在选择“文本字段”时才应显示“眼睛按钮”。我已经尝试过使用“ isFirstResponder”,但这似乎不起作用。有什么想法如何处理吗?在下面的图片中,未选择文本字段。
更新
委托函数“密码确实已更改”可以正常工作。我唯一需要的是,如果不再选择文本字段,则按钮应该隐藏。添加委托函数“ beging”或“ endEditing”不起作用。如果用户键入某些内容,然后取消选择该文本字段并再次选择它,这将导致另一个失败,即删除文本。
@IBAction func passwordDidChange(_ sender: Any) {
if self.passwordTextField.text == "" && self.passwordTextField.isFirstResponder != true{
self.eyeOpenButton.isHidden = true
}else {
self.eyeOpenButton.isHidden = false
}
答案 0 :(得分:2)
您可以尝试这样的事情。
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
}
}
答案 1 :(得分:0)
您需要使用UITextfieldDelegate
方法进行处理。实现这些方法并听取更改并采取相应措施。