UITextField明暗文输入文字被清空
2020-02-04 本文已影响0人
HusterYP
UITextField
设置密码输入时,需要设置isSecureTextEntry
(Swift
)属性;但是如果明暗文切换,再次切换到暗文,即密码输入,若此时再输入,会使原来的输入清空;在网上找到解决办法如下:摘自:https://stackoverflow.com/questions/7305538/uitextfield-with-secure-entry-always-getting-cleared-before-editing
extension PasswordInputView: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let updateString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
inputTF.text = updateString
let selectedRange = NSMakeRange(range.location + string.count, 0)
let from = textField.position(from: textField.beginningOfDocument, offset:selectedRange.location)
let to = textField.position(from: from!, offset:selectedRange.length)
textField.selectedTextRange = textField.textRange(from: from!, to: to!)
textField.sendActions(for: UIControl.Event.editingChanged)
return false
}
}