Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how text length of a UITextView can be fixed?

I have a UITextView, user can write maximum 160 character in the textView. How can i fixed the maximum text length of a UITextView?

like image 717
faisal Avatar asked Sep 11 '25 04:09

faisal


1 Answers

This chunk of code also works with Copy/Paste, but also copes with situation when trying to paste number of characters that will make the text view exceed the limit. In that case, only first characters of the string are pasted.

#define MAX_LENGTH 15 // Whatever your limit is
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSUInteger newLength = (textView.text.length - range.length) + text.length;
    if(newLength <= MAX_LENGTH)
    {
        return YES;
    } else {
        NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length);
        textView.text = [[[textView.text substringToIndex:range.location] 
                                            stringByAppendingString:[text substringToIndex:emptySpace]]
                                         stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]];
        return NO;
    }
}
like image 169
manicaesar Avatar answered Sep 12 '25 18:09

manicaesar