How to limit the number of characters in a UITextField or UITextView

by

Very common user experience we come across when using UITextField and UITextview is to limit the number of characters.

It’s implementation is straightforward using their standard delegates implementing either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).


For UITextField:


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField.text?.count ?? 0) +  (string.count - range.length) >= characterLimit{
        return false
    }
    
    return true
}


For UITextView:


func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if (textView.text?.count ?? 0) +  (text.count - range.length) >= characterLimit{
        return false
    }

    return true
}



More Articles

Recommended posts