我有一个 UITextField,我想将其长度限制为 4 个字符,这是它的代码:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = acRegTextField.text else { return true }
let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 4 // Bool
}
问题是,使用这段代码,当 acRegTextField 为 4 个字符时,我的其他文本框停止了。
老实说我不明白...任何帮助将不胜感激
谢谢
最佳答案
如果您的 View 中有许多文本字段并将委托(delegate)分配给它们,则 shouldChangeCharactersInRange 将应用于所有文本字段。所以你可以做的是,如果你已经有一个应该只包含 4 个字符的文本字段的导出 - 然后只需比较这个文本字段是你想要验证的 - 注意 === 比较引用。例如:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if acRegTextField === textField {
guard let text = acRegTextField.text else { return true }
let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 4 // Bool
}
return true
}
关于ios - 限制 UITextfield 长度限制了我所有的 UITextfields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507511/