How to limit characters in UITextView iOS

smithyy picture smithyy · Jul 29, 2015 · Viewed 8.7k times · Source

I have a UITextView and i would like to limit the number of characters a user can input. i have also tried to display a warning if the textfield is empty but to no luck.

textview.h

@property (nonatomic,strong) IBOutlet UITextView *textField;
@property (nonatomic, retain) NSString *userText;

textview.m

- (IBAction)next:(id)sender {

    self.userText = self.textField.text;

    if ([self.textField.text length] == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                                message:@"Enter some text"
                                                               delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
        }
}

here is the text limit method that does not seem to work,

- (BOOL)textView:(UITextView *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if(range.length + range.location > textField.text.length)
    {
        return NO;

    } else {

    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return newLength <= 70;
    return (textField.text.length <= 70);
}
}

Answer

Nik picture Nik · Jul 29, 2015

1) add UITextViewDelegate in your viewcontroller like this

@interface ViewController : UIViewController <UITextViewDelegate>

Each time a user types a character on the keyboard, just before the character is displayed,following method get called. This is a handy location to test the characters that a user is typing and disallow specific characters you want to restrict.

textView:shouldChangeCharactersInRange:replacementString

2) then write following code. instead of 140 you can put whatever number you want.

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

For more help take a look at UItextView

Swift 2.0 solution

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    return textView.text.characters.count + (text.characters.count - range.length) <= textViewLimit
}