【发布时间】:2018-03-21 15:18:02
【问题描述】:
我的代码中的 Login/SIgnup 控制器中有两个 UITextField(电子邮件、密码)(这里是 example),这样用户显然可以插入登录名/密码来注册/登录。
在shouldChangeCharactersIn方法中,我检查用户插入的数据,然后执行loginButtonChangeState()方法,激活登录按钮,以防插入的数据正确:
- 电子邮件:应该是电子邮件,用 RegEx 进行检查。
- 密码:长度至少应为 6 个字符
这里是方法的内容:
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
}
此代码运行良好,但以下操作序列破坏了它,并且登录按钮保持活动状态。
- 输入电子邮件,例如t@t.com
- 比输入密码,例如123456
- 登录按钮 - 激活
- 再次点击/转到地址字段
- 点击/返回密码字段
- 点击键盘退格按钮 à 登录按钮保持活动状态,尽管它本应变为非活动状态。
之所以保持活动状态,是因为在使用退格键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 是“空格键”,但textField.text仍然包含“123456”。
视频可以看这里:https://github.com/AdAvAn/ShouldChangeCharactersInRange/raw/master/shouldChangeCharactersIn.gif
问题:
如何更正该方法的工作,以便在键盘上按退格键后“登录”按钮变为非活动状态(最好不要清除密码 UITextField 的内容)?
UDP:25.03.18
只有isSecureTextEntry 参数为真的字段才会出现此问题。
到目前为止我还没有找到更漂亮的解决方案,除了设置password.clearsOnBeginEditing = true。这允许您在每次触发 func textFieldDidBeginEditing (_ textField: UITextField) 时清除密码字段的内容。
【问题讨论】:
-
你能不能试着用
let existingText = textField.text as NSString? let changedText = existingText?.replacingCharacters(in: range, with: string)替换你的逻辑 -
问题是在按下空格的那一刻textField.text包含了之前的值。您的代码只会在行尾添加一个空格。在我的方法中有它的类比。 let textRange = Range (range, in: text) { let updatedText = text.replacingCharacters (in: textRange, with: string)
标签: ios swift uitextfielddelegate