UITextField設置密文延時處理---仿QQ登陸密碼輸入

系統的UITextField輸入的時候最後一個字符會有1-2s的效果展現, 效果以下:ide

爲了解決這個問題, 能夠用字符 "" 替換, 替換後效果以下:ui

 

用到的是UITextField的代理方法textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool, 進行替換, 代碼以下:spa

import UIKit

class MLSecureTextEntryTextField: UIView {
    
    var text = ""
    
    var mTextField = UITextField()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    fileprivate func setupUI(){
        mTextField = UITextField.init(frame: self.bounds)
        mTextField.keyboardType = .default
        mTextField.font = UIFont.systemFont(ofSize: 15)
        mTextField.isSecureTextEntry = true
        mTextField.delegate = self
        addSubview(mTextField)
    }
    
    open var placeholder = "" {
        didSet{
            mTextField.placeholder = placeholder
        }
    }
    
    var font = UIFont.systemFont(ofSize: 11) {
        didSet{
            mTextField.font = font
        }
    }
    
    var textColor = UIColor.blue {
        didSet{
            mTextField.textColor = textColor
        }
    }
    
    var keyboardType = UIKeyboardType.default {
        didSet{
            mTextField.keyboardType = keyboardType
        }
    }
}


extension MLSecureTextEntryTextField: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.count == 0 {
            // 刪除
            text.remove(at: text.index(before: text.endIndex))
        }else{
            // 添加
            text = text + string
        }
        
        var textStr = ""
        for _ in text {
            textStr = textStr + "●"
        }
        
        textField.text = textStr
        return false
    }
}

 

使用方法:代理

textField =   MLSecureTextEntryTextField(frame: CGRect(x: 20, y: 150, width: 200, height: 30))
textField?.placeholder = "替換後密文"
view.addSubview(textField!)
NSLog("textField值: %@", textField?.text ?? "")
相關文章
相關標籤/搜索