Created
September 27, 2019 10:20
-
-
Save heitara/2d7cdaa2492d8f32e433f6320c8fe68d to your computer and use it in GitHub Desktop.
Password Text Field on iOS 12 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() | |
} | |
func commonInit() { | |
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