textField shouldChangeCharactersInRange 在用户操作之后执行一步 [英] textField shouldChangeCharactersInRange is executing one step behind user action
问题描述
我有一个 textField
,用户可以在其中输入电子邮件地址.我想在输入文本成为有效电子邮件地址的那一刻激活提交按钮.
I have a textField
into which the user types an email address. I want to activate the submit button at the instant the input text becomes a valid email address.
验证有效,但 shouldChangeCharactersInRange
中的代码似乎在用户输入之后执行一步.因此,当电子邮件有效时,用户仍然必须在按钮更改之前再点击一个键.同样,如果电子邮件地址无效,则按钮不会更改,直到再点击一个键.
The validation works, but the code in shouldChangeCharactersInRange
appears to execute one step behind the user input. So when the email is valid, the user still has to tap one more key before the button changes. And likewise, if the email address becomes invalid, the button doesn't change until one more key is tapped.
请注意,这也会发生在设备上,而不仅仅是在模拟器中.
Note that this happens on the device too, not just in the simulator.
代码如下:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) {
if emailIsValidFormat(textField.text) {
emailSubmitButton.alpha = 1
} else {
emailSubmitButton.alpha = 0.4
}
}
推荐答案
调用此方法时文本尚未更改.您必须使用range
和replacementString
来构造电子邮件地址,然后进行验证.
The text hasn't changed yet when this method is called. You have to userange
and replacementString
to construct the email address, and then verify that.
这篇关于textField shouldChangeCharactersInRange 在用户操作之后执行一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!