Limit number of characters in uitextview
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return textView.text.length + (text.length - range.length) <= 140;
}
This accounts for users cutting text, or deleting strings longer than a single character (ie if they select and then hit backspace), or highlighting a range and pasting strings shorter or longer than it.
Swift 4.0 Version
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return textView.text.count + (text.count - range.length) <= 140
}
You should be looking for an empty string instead, as the apple reference says
If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.
I think the check you actually want to make is something like [[textView text] length] - range.length + text.length > 140
, to account for cut/paste operations.