我正在搜索以限制用户可以在文本字段中输入的字符数。
我发现这种方法并且它运作良好
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 25
但是现在,我想为2个不同的文本字段设置不同的限制。
有人有线索吗?
答案 0 :(得分:0)
您可以通过设置textField == yourTextField
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == textField1 {
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 25
}
else if textField == textField2 {
// set for textField2
}
return false
答案 1 :(得分:0)
您可以为每个文本字段分配标记属性,稍后您可以使用它。
分配标签属性:
firstTextField.tag = 2015
secondTextField.tag = 2016
thirdTextField.tag = 2017
稍后,您可以像这样使用它:
*//you can also use if else cases here*
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
switch textField.tag {
case 2015:// set your rules here for firstTextField
case 2016:// set your rules here for secondTextField
case 2017:// set your rules here for thirdTextField
default:print(" definitely it works")
}
}