UITextField设置密文延时处理---仿QQ登录密码输入
系统的UITextField输入的时候最后一个字符会有1-2s的效果展示, 效果如下:
为了解决这个问题, 可以用字符 "●" 替换, 替换后效果如下:
用到的是UITextField的代理方法textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool, 进行替换, 代码如下:
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 ?? "")