[英]Limit TextField Input to Capitals letters, Numbers and Character limit of 6?
我在网上进行搜索,发现了很多有关限制TextField的示例,但找不到有关限制多个因素的任何示例。 我正在工作的代码弄乱了输入内容,我弄不清原因。
这是我的代码:(注意:我已经设置了委托)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = LPinput.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
return newLength <= limitLength
}
这是我在TextField中键入的内容:
餐饮
这是TextField中显示的内容:
FoOoOD
请帮忙!
就像@rmaddy所说的那样,问题在于您正在修改UITextField.text
属性,然后返回true,这会导致在您的问题中出现重复的行为,因此我对此进行了更改,请首先检查textLength,然后修改文本并返回始终为false,以避免添加重复字符,请尝试使用此代码
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = LPinput.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
if(newLength <= limitLength)
{
LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
}
return false
}
希望这对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.