简体   繁体   中英

How to unclear UITextField secure text entry in Swift?

When I use default Security text Entry in UITextField in Swift Language after type type text once UITextField.

第一次输入文本时的图像

Once loss focus from UITextField after try to edit Secure text then UITextField is first reset and after it start put new text in UITextField.

用于尝试编辑旧文本的图像

How to edit old Secure Text without Storing data into Any Kind of String object

I'd suggest to create a custom UITextField class and override become​First​Responder() method do add your desired functionality:

You can override this method in your custom responders to update your object's state or perform some action such as highlighting the selection. If you override this method, you must call super at some point in your implementation.

The custom Class should be similar to:

class CustomSecureTextField: UITextField {
    override func becomeFirstResponder() -> Bool {
        super.becomeFirstResponder()

        if !isSecureTextEntry { return true  }

        if let currentText = text { insertText(currentText) }

        return true
    }
}

The logic of the implementation of becomeFirstResponder as follows:

By default, the secured-entry text field clears the inserted text when it is become first responder text, so what's happening in CustomSecureTextField that if the text field is secured-entry, it will re-insert the current inserted text -after clearing it-, but you have to make sure that the text field input is secured (that's the purpose of adding if !isSecureTextEntry { return true } ) or the text will be duplicated (re-inserted) each time the text field becomes first responder.

Output:

Note that both of text fields are types of CustomSecureTextField :

在此处输入图片说明

This answer helped me to figure out this problem.

   textField.isSecureTextEntry = true 

following property not gonna work if you make testField isSecureTextEntrysecure property makes true .

   textField.clearsOnBeginEditing = false

There is an issue with the @Ahmd F solution when you simply tap on the field it will automatically add the text to the field I have resolved that in the below code thanks

override open func becomeFirstResponder() -> Bool {
    super.becomeFirstResponder()
    if !isSecureTextEntry { return true}
    if let currrentText = text {
        self.text = ""
        insertText(currrentText)
    }
    return true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM