我的代码中的Login / SIgnup控制器中有两个UITextField(电子邮件,密码)(这里是example),因此用户显然可以插入登录/密码来注册/登录。
在方法shouldChangeCharactersIn
中,我检查用户插入的数据,然后执行方法loginButtonChangeState()
,激活登录按钮,以防数据插入正确:
以下是该方法的内容:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange, with: string)
switch textField {
case _ where textField.isIdentical(with: email) : state[textField] = chekMail(for: updatedText)
case _ where textField.isIdentical(with: password) : state[textField] = chekPass(for: updatedText)
default: break
}
loginButtonChangeState()
print("shouldChangeCharactersIn: textField.text:\(text), replacementString: \(string)")
}
return true
}
此代码运行良好,但以下操作序列会破坏它,并且登录按钮会保持活动状态。
为什么它保持活动的原因是因为在使用退格后shouldChangeCharactersIn
方法传输UITextField
的旧内容后,可以在控制台日志中看到
shouldChangeCharactersIn: textField.text:, replacementString: t
shouldChangeCharactersIn: textField.text:t, replacementString: @
shouldChangeCharactersIn: textField.text:t@, replacementString: t
shouldChangeCharactersIn: textField.text:t@t, replacementString: .
shouldChangeCharactersIn: textField.text:t@t., replacementString: c
shouldChangeCharactersIn: textField.text:t@t.c, replacementString: o
shouldChangeCharactersIn: textField.text:t@t.co, replacementString: m
shouldChangeCharactersIn: textField.text:, replacementString: 1
shouldChangeCharactersIn: textField.text:1, replacementString: 2
shouldChangeCharactersIn: textField.text:12, replacementString: 3
shouldChangeCharactersIn: textField.text:123, replacementString: 4
shouldChangeCharactersIn: textField.text:1234, replacementString: 5
shouldChangeCharactersIn: textField.text:12345, replacementString: 6
shouldChangeCharactersIn: textField.text:123456, replacementString:
在这行“ shouldChangeCharactersIn:textField.text:123456,replacementString:”中,replacementString
是“ space sighn ”,但{ {1}}仍然包含“ 123456 ”。
视频可以在这里看到:https://github.com/AdAvAn/ShouldChangeCharactersInRange/raw/master/shouldChangeCharactersIn.gif
问题:
如何更正方法的工作,以便在键盘上录制退格键后“登录”按钮变为非活动状态(理想情况下不清除密码UITextField的内容)?
UDP:25.03.18
只有textField.text
参数为true的字段才会出现此问题。
到目前为止,除了设置isSecureTextEntry
之外,我还没有找到更漂亮的解决方案。这允许您在每次触发func password.clearsOnBeginEditing = true
时清除密码字段的内容。
答案 0 :(得分:1)
我没有做太多,只是删除了一些你的线。无论是删除字符还是添加字符,updatedText现在都应该正确反映文本字段的当前文本。如果你的代码仍然不起作用,那么你必须检查你的switch语句并检查方法。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let previousText:NSString = textField.text! as NSString
let updatedText = previousText.replacingCharacters(in: range, with: string)
print("updatedText > ", updatedText)
//the rest of your code
return true
}
我希望这会有所帮助。