UITextView character counter

So here’s a programming problem I recently came across. Again there’s lots of answers out there and more than one way to skin a cat so to speak. However here’s my method of implementing a simple character counter that will display an UIAlertView when the character limit is reached.

Download Xcode Project File here

First you need to add the UITextView delegate in your header file, and connect the relevant UITextView as a delegate.

@interface EmailViewController : UIViewController <UITextViewDelegate>

You can then put in your implementation file :-

//check for number of characters in UITextView
- (void)textViewDidChange:(UITextView *)textView {
//create NSString containing the text from the UITextView
    NSString *substring = [NSString stringWithString:textView.text];

    //if message has text show label and update with number of characters using the NSString.length function
    if (substring.length > 0) {
        countLabel.hidden = NO;
       countLabel.text = [NSString stringWithFormat:@"%d characters", substring.length];
    }
    //if message has no text hide label
    if (substring.length == 0) {
        countLabel.hidden = YES;
    }
    //if message length is equal to 512 characters display alert view
    if (substring.length == 512) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your message can't be longer than        512 characters" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        //if character count is over max number change label to red text
        countLabel.textColor = [UIColor redColor];
    }
    //if message is less than 512 characters change font to black
    if (substring.length < 512) {
        sendDate.textColor = [UIColor blackColor];
    }
}

3 thoughts on “UITextView character counter

Leave a Reply