Kevin Kevin - 1 month ago 18
iOS Question

Max Character Limit for TextField

I am looking to cap the amount of characters a user can type into a textfield at 14. Here is the code that I have found documentation on.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let currentCharacterCount = userNameTextField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 14
}


but I do not feel that I am implementing this correctly. I have set

userNameTextField.delegate = self


in the viewDidLoad, and I am conforming to the
UITextFieldDelegate
protocol.

Answer

You state you are using Swift 3. The signature of many methods changed in Swift 3. You need to use:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
}

Not the old signature posted in your question.

If it's still not being called, then you never set the text field's delegate property.