UITextField明暗文输入文字被清空

UITextField设置密码输入时,需要设置isSecureTextEntrySwift)属性;但是如果明暗文切换,再次切换到暗文,即密码输入,若此时再输入,会使原来的输入清空;在网上找到解决办法如下:摘自: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
    }
}

你可能感兴趣的:(UITextField明暗文输入文字被清空)