Jp4Real
Jp4Real

Reputation: 2002

Limiting UITextfield length limits all my UITextfields

I have a UITextField that I want to limit the lenght to 4 characters here's the code for it :

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
    }

problem is, with this code, my other text box gets stopped when acRegTextField as 4 char in it.

I honestly don't get it... any help would be appreciated

thanks

Upvotes: 0

Views: 68

Answers (2)

totiDev
totiDev

Reputation: 5275

If you have numerous textfields on your view and assign the delegate to them then shouldChangeCharactersInRange will apply to all the textfields. So what you can do is if you already have an outlet to the textfield that should contain just 4 characters - then just compare this textfield is the one you want to validate - note the === compares the reference. eg:

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
}

Upvotes: 2

emrys57
emrys57

Reputation: 6806

This is a method from UITextFieldDelegate. To make this work, you must have said somewhere

myTextField.delegate = myClass

Every text field you say that for will get the same delegate. If you don't want the limit to apply to a particular textField, then don't set the delegate for that textField.

Upvotes: 0

Related Questions