[英]Swift5: TextField Minimum and Maximum Character Limit Validation
I am trying to validate Minimum 6 characters and Maximum 20 characters in TextField.我正在尝试验证 TextField 中的最少 6 个字符和最多 20 个字符。 Below is the code validation .
下面是代码验证。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let curruntCharachterCount = textField.text?.count ?? 0
if range.length + range.location > curruntCharachterCount{
return false
}
let newLength = curruntCharachterCount + string.count - range.length
return newLength <= 20
}
How should i set Minimum character length validation.我应该如何设置最小字符长度验证。 Please suggest.
请建议。
You can do like below你可以像下面这样
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)
if updatedText.count <= 6 {
print("minimum 6")
}else if updatedText.count >= 20{
print("max 20")
return false
}
}
return true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.