How to toggle a UITextField secure text entry (hide password) in Swift?

前端 未结 24 2814
时光取名叫无心
时光取名叫无心 2021-01-30 02:00

I currently have a UITextfield with an eye icon in it that when pressed is supposed to toggle the secure text entry on and off.

I know you can che

24条回答
  •  不知归路
    2021-01-30 02:58

    If you need TextField with similar feature in multiple places its best to subclass the UITextField like follwing example -

    import UIKit
    
    class UIShowHideTextField: UITextField {
    
        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.setImage(UIImage(named: "password_show") , for: .normal)
            rightButton.addTarget(self, action: #selector(toggleShowHide), for: .touchUpInside)
            rightButton.frame = CGRect(x:0, y:0, width:30, height:30)
    
            rightViewMode = .always
            rightView = rightButton
            isSecureTextEntry = true
        }
    
        @objc
        func toggleShowHide(button: UIButton) {
            toggle()
        }
    
        func toggle() {
            isSecureTextEntry = !isSecureTextEntry
            if isSecureTextEntry {
                rightButton.setImage(UIImage(named: "password_show") , for: .normal)
            } else {
                rightButton.setImage(UIImage(named: "password_hide") , for: .normal)
            }
        }
    
    }
    

    After which you can use it in any ViewController,

    class ViewController: UIViewController {
    
        @IBOutlet var textField: UIShowHideTextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            textField.becomeFirstResponder()
        }
    
    }
    

提交回复
热议问题