2
votes

I'm searching to limit the number of characters that an user can enter in a textfield.

I find this method and it's working very well

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

But now, I wanted to put different limits for 2 different textfields.

Does someone have a clue?

2
Use the textField parameter to distinguish between different textviews if you want to use the same delegate for them. - A-Live

2 Answers

0
votes

You can achieve this by setting 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
0
votes

You can assign tag property for every text field and later you can use it.

Assigning tag property:

firstTextField.tag = 2015
secondTextField.tag = 2016
thirdTextField.tag = 2017

Later, you can use it like this:

*//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")
    }
}