Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of characters in uitextview

I am giving a text view to tweet some string .

I am applying the following method to restrict the number of characters to 140 in length.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{    return [[textView text] length] <= 140; } 

The code is working nicely except the first condition that backspace is not working. suppose that I have reached the limit of 140 characters so that the method will give me false and the user can not insert more characters but after that when I try to delete some characters the text view behave as it is disabled .

So the question is: "How to delete characters from textview.text or re-enable the text view?"

like image 400
harshalb Avatar asked Mar 22 '10 12:03

harshalb


People also ask

How do I limit the number of characters in UITextField or UITextView?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).

How do I limit the number of characters in a text field in Swift?

Create textLimit method This is the first step in limiting the characters for a text field or a text view. We need to create a method that will limit the the number of characters based on the current character count and the additional/new text that will get appended to the current value of the text field or text view.

What is Textfield delegate in Swift?

A set of optional methods to manage the editing and validation of text in a text field object.


2 Answers

- (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 } 
like image 189
Tim Avatar answered Sep 19 '22 11:09

Tim


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.

like image 29
David Gelhar Avatar answered Sep 20 '22 11:09

David Gelhar