How can I change the dots to another character on password field in iOS Swift

后端 未结 3 449
别跟我提以往
别跟我提以往 2021-01-02 17:13

I have a Text Field and I would like to replace the default dot character to something else when the password is hidden. Is there any way to do this easily?

3条回答
  •  离开以前
    2021-01-02 17:48

    Swift 5 ready to use, updated version of crifan answer:

    import UIKit
    
    class PasswordTextField: UITextField, UITextFieldDelegate {
        var realText: String {
            didSet {
                updateMaskStr()
            }
        }
        let maskChar: Character
        
        init(
            frame: CGRect = .zero,
            maskChar: Character = "*"
        ) {
            realText = ""
            self.maskChar = maskChar
            super.init(frame: frame)
            setupActions()
            setupDelegates()
        }
        
        private func setupActions() {
            addTarget(self, action: #selector(textFiledEditingChanged(textField:)), for: .editingChanged)
        }
        
        private func setupDelegates() {
            delegate = self
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func updateMaskStr(){
            //change real text to mask char
            var maskStr = ""
            
            for _ in realText {
                maskStr += String(self.maskChar)
            }
            
            text = maskStr
        }
        
        @objc
        private func textFiledEditingChanged(textField: UITextField) { updateMaskStr() }
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let curText = realText
            let updatedStr:String = (curText as NSString).replacingCharacters(in: range, with: string)
            realText = updatedStr
            return false
        }
    }
    

提交回复
热议问题