TextField密文,再次编辑,取消清空之前的内容

textField.isSecureTextEntry = true 密文输入

使用TextField密文输入时,结束输入后(或者切换密文/明文 isSecureTextEntry ),再次编辑时会出现,先清空之前的内容,然后再正常输入

目的:密文输入时,跟明文输入一样

调用:textField. isSecureBeginClear = false 一句代码开启 反之则关闭

extension UITextField {
    
    private struct AssociatedObjectByHQ {
        static var clear = "AssociatedObjectByHQ.isSecureBeginClear"
        static var setSecureTextEntryChanged = false
    }
    
    public var isSecureBeginClear: Bool {
        get {
            objc_getAssociatedObject(self, &AssociatedObjectByHQ.clear) as? Bool ?? true
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObjectByHQ.clear, newValue, .OBJC_ASSOCIATION_COPY)
            if !newValue {
                if !AssociatedObjectByHQ.setSecureTextEntryChanged {
                    AssociatedObjectByHQ.setSecureTextEntryChanged = true
                    guard let m1 = class_getInstanceMethod(self.classForCoder, Selector(("setSecureTextEntry:"))) else {
                        return
                    }
                    guard let m2 = class_getInstanceMethod(self.classForCoder, #selector(hq_setSecureTextEntry(_:))) else {
                        return
                    }
                    method_exchangeImplementations(m1, m2)//这里如果使用kvo去监听isSecureTextEntry 在iOS 14之前会崩溃, isSecureTextEntry是一个协议方法,这里采用方法交换
                }
                 
                NotificationCenter.default.addObserver(self, selector: #selector(textDidBeginEditingNotificationFunc(_:)), name: UITextField.textDidBeginEditingNotification, object: nil)
            } else {
                NotificationCenter.default.removeObserver(self)
                endEditing(true)
            }
        }
    }
     
    @objc private func hq_setSecureTextEntry(_ new: Bool) {
        hq_setSecureTextEntry(new)
        if !isSecureBeginClear {
            if let text = self.text, isFirstResponder {
                self.text = ""
                self.insertText(text)
                self.insertText("")
            }
        }
    }
    
    @objc private func textDidBeginEditingNotificationFunc(_ notification: NSNotification) {
        if let textField = notification.object as? UITextField, textField == self, textField.isSecureTextEntry {
            if let text = textField.text {
                textField.text = ""
                textField.insertText(text)
                textField.insertText("")//防止再次输入时最后一个字符为明文
            }
        }
    }
}

你可能感兴趣的:(TextField密文,再次编辑,取消清空之前的内容)