Adam G
Adam G

Reputation: 1188

UITextView - Max line breaks

When using a UITextView to gather user input in Objective-C, how can I limit the user from trying to do more than one line break at a time?

So, this would be fine:

This is my text.

Here is some more text.

But this would not be fine:

This is my text.




Here is some more text way down here.

Upvotes: 1

Views: 291

Answers (1)

FabKremer
FabKremer

Reputation: 2169

In your ViewController.h add UITextViewDelegate:

YourViewController : UIViewController <UITextViewDelegate> 

and in the ViewController.m implement the method textView:shouldChangeTextInRange:replacementText: this way:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        NSMutableString *futureString = [textView.text mutableCopy];
        [futureString insertString:text atIndex:range.location];

        NSRange rangeOflineBreaks = [futureString rangeOfString:@"\n\n\n"];
        if (rangeOflineBreaks.location != NSNotFound) {
            return NO;
        }
    }
    return YES;
}

This will be executed every time before the user wants to add some text to the textView and wont let him add another line break if it notices that he wants to add a line break and it finds, after trying adding it (that's why the futureString name) a triple line break mode. In that case he wont let the user add another line break.

Try it out, it should work :)

PS: Don't forget to set your textView delegate the viewController in the viewDidLoad (yourTextView.delegate = self)

Upvotes: 1

Related Questions