Tuesday, June 12, 2012

Limit the number of characters in UITextView

#define MAX_LENGTH 50

// UITextView delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {    
    NSLog(@"type %d char", myTextView.text.length);    
    if (myTextView.text.length >= MAX_LENGTH && range.length == 0)
        NSLog(@"max length is reached");
        return NO; // return NO to not change text

1 comment:

  1. This isn't good enough when the user pastes some long text. You might want in that case to truncate the text to the maximum length. This is not trivial.