Created
September 27, 2019 10:23
-
-
Save heitara/5a4fc64319ec300a4a2d8545e8f2c560 to your computer and use it in GitHub Desktop.
Password Text Field on iOS 13+ with an icon on the right to reveal the password
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UIShowHideTextField: UnderlinedTextField { | |
let rightButton = UIButton(type: .custom) | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
commonInit() | |
} | |
required override init(frame: CGRect) { | |
super.init(frame: frame) | |
commonInit() | |
} | |
//the code that properly resizes the icon | |
override func rightViewRect(forBounds bounds: CGRect) -> CGRect { | |
return CGRect(x: bounds.width - 32, y: bounds.midY - 16, width: 32, height: 32) | |
} | |
func commonInit() { | |
//this is not taken into account | |
rightButton.frame = CGRect(x:0, y:0, width:32, height:32) | |
rightButton.setImage(UIImage(named: "eye_inactive") , for: .normal) | |
rightButton.imageView?.contentMode = .scaleAspectFit | |
rightButton.imageEdgeInsets = UIEdgeInsets(top: 3.0, left: 3.0, bottom: 3.0, right: 3.0) | |
rightButton.addTarget(self, action: #selector(toggleShowHide), for: .touchUpInside) | |
rightButton.translatesAutoresizingMaskIntoConstraints = false | |
rightViewMode = .always | |
rightView = rightButton | |
isSecureTextEntry = true | |
self.addTarget(self, action: #selector(textDidChange), for: .editingChanged) | |
} | |
@objc func toggleShowHide(button: UIButton) { | |
toggle() | |
} | |
func toggle() { | |
if (text == "") { | |
return | |
} | |
isSecureTextEntry = !isSecureTextEntry | |
if isSecureTextEntry { | |
rightButton.setImage(UIImage(named: "eye_not_visible") , for: .normal) | |
} else { | |
rightButton.setImage(UIImage(named: "eye_visible") , for: .normal) | |
} | |
} | |
@objc func textDidChange() -> Void { | |
if (text == "") { | |
rightButton.setImage(UIImage(named: "eye_inactive") , for: .normal) | |
} else if isSecureTextEntry { | |
rightButton.setImage(UIImage(named: "eye_not_visible") , for: .normal) | |
} else { | |
rightButton.setImage(UIImage(named: "eye_visible") , for: .normal) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment