[英]Swift UITextfield Delegate Function "shouldChangeCharactersIn" - How can I stop editing for a second UITextfield?
I have a problem, I have two Textfields and want a max length of 20 Characters for both.我有一个问题,我有两个文本字段,并且两个文本字段的最大长度均为 20 个字符。
I use the following code but it only works for my first Textfield.我使用以下代码,但它仅适用于我的第一个文本字段。 What did I wrong?我做错了什么? I hope someone can help me.我希望有一个人可以帮助我。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField === nameTextField {
let currentText = nameTextField.text
guard let stringRange = Range(range, in: currentText!) else {
return false
}
let updateText = currentText?.replacingCharacters(in: stringRange, with: string)
return updateText?.count ?? 0 < 20
} else if textField === numberTextField {
let currentText = numberTextField.text
guard let stringRange = Range(range, in: currentText!) else {
return false
}
let updateText = currentText?.replacingCharacters(in: stringRange, with: string)
return updateText?.count ?? 0 < 20
}
return true
}
You probably forgot to set the delegate
for the second one.您可能忘记为第二个设置delegate
。
Also no need for this complex logic: Just keep the first 20 like:也不需要这个复杂的逻辑:只需保留前 20 个:
textView.text = String(textView.text.prefix(20))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.