Reputation: 2274
The problem is that the "Eye Button" should only be displayed while the Textfield is selected. I have tried it with "isFirstResponder" but that doesn't seem to be working. Any ideas how to handle this? In the picture down below the textfield is not selected.
Update
The delegate function "password did change" works fine. The only thing I need is that the button should hide if the textfield is not selected anymore. Adding the delegate functions "beging" or "endEditing" doesn't work. It just causes another fail where the text gets deleted if the user types something in, deselects the textfield and selects it back again.
@IBAction func passwordDidChange(_ sender: Any) {
if self.passwordTextField.text == "" && self.passwordTextField.isFirstResponder != true{
self.eyeOpenButton.isHidden = true
}else {
self.eyeOpenButton.isHidden = false
}
Upvotes: 0
Views: 854
Reputation: 2240
You could try something like this.
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
}
}
Upvotes: 2
Reputation: 5060
You need to handle this in UITextfieldDelegate
method. Implement those methods and listen to changes and act accordingly.
Upvotes: 0