Iphone – how text length of a UITextView can be fixed

iphoneuitextview

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

Best Answer

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;
    }
}