【问题标题】:What main difference textFieldDidChange and shouldChangeCharactersIn method, the delegate of UITextFieldDelegate?textFieldDidChange 和 shouldChangeCharactersIn 方法的主要区别是什么,UITextFieldDelegate 的委托?
【发布时间】:2021-04-21 03:34:11
【问题描述】:
【问题讨论】:
-
什么是textFieldDidChange? UITextFieldDelegate 中没有这样的东西。只有textFieldDidChangeSelection。你把它和别的东西混淆了吗?对于shouldChangeCharactersIn,请参阅my explanation here,以限制文本字段中的字符数。
标签:
ios
swift
uitextfield
uitextviewdelegate
【解决方案1】:
简单来说,textDidChange 发生在 Textfield 中键入任何文本并且您希望在 TextField 上键入文本以检查验证或任何内容时...
func textDidChange(_ textField: UITextField) {
guard let email = emailTextField.text, !email.isEmpty, email.isValidEmail() else {
//Write your code here...
return }
guard let password = passwordTextField.text, !password.isEmpty else {
//Write your code here..
return }
//Write your success code.
}
并且shouldChangeCharactersIn 在任何键入的键即将在 Textfield 中打印之前发生事件。这样您就可以更改该密钥并允许或限制该密钥。
例如:如果用户在密码文本字段中输入空格,您可以限制该键并且空格将永远不会在文本字段中打印。
在下面的代码中,我限制了我的文本字段中的空格(“”)键。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if range.location == 0 && string == " " {
return false
}
return true
}