[英]Using `textField:shouldChangeCharactersInRange:`, how do i found that characters are mismatch?
I'm using the code below for setting validation of textfield as it should not enter above 15 character length . 我正在使用下面的代码来设置文本字段的验证,因为它不应输入超过15个字符的长度。
let limitLength = 15
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
} else if textField == txtConfirmpassword { // if textfield confirm password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
return true
}
there are two textfield as password and confirm password i want to check validation whether they have same string or not? 有两个文本字段作为密码并确认密码,我想检查验证它们是否具有相同的字符串?
"textField:shouldChangeCharactersInRange" is method we need to use but i don't know how to compare while user is entering and i need to display alert message that they are not same Note :- it should not compare while click on any button. “ textField:shouldChangeCharactersInRange”是我们需要使用的方法,但是我不知道如何在用户输入时进行比较,并且我需要显示警报消息,提示它们不一样。注意:-单击任何按钮时都不应进行比较。
try like this 这样尝试
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count
return newLength <= limitLength
} else if textField == txtConfirmpassword { // if textfield confirm password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count
if newLength <= limitLength && txtPassword.text.hasPrefix("\(text)\(string)") {
return true
} else {
// here u can show alert
textField.resignFirstResponder()
return false
}
}
return true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.