1

I'm using UITextView in my application, i want user to enter maximum 5 lines of text, I've been spending a few days on google but still have no luck, can some one please help!!

PS: Not limit number of characters but number of "LINES"

I've tried finding number of lines and use this method textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text , return NO when limit is reached but the back space button doesn't work after limit reached.

Thanks!

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Fried Rice
  • 3,295
  • 3
  • 18
  • 27
  • Possible duplicate of http://stackoverflow.com/questions/5225763/limit-the-number-of-lines-for-uitextview and http://stackoverflow.com/questions/411398/limiting-text-in-a-uitextview – phi Oct 21 '11 at 14:08
  • -1, this question does not show any effort. Apart from looking for other people's solutions on Google, what have you already tried? – Rob Oct 21 '11 at 14:17
  • +1 for this question, he said he tried something :) – caribbean Sep 18 '13 at 05:26

2 Answers2

2

If the lines are not automatically wrapped you could use this:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
        if([text isEqualToString:@"\n"]) {
            rows++;
        if(rows >= maxNumberOfLines){
            //Exit textview
             return NO;
            }
       }
      return YES;
}

This should work, but it's not the best way to deal with it.

It would probably be better to use the size of the string and compare it to the contentsize of the textview to limit it.

Wolfert
  • 974
  • 6
  • 12
  • 1
    I've tried finding number of lines and use this method textView:`(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text` , return NO when limit is reached but the back space button doesn't work after limit reached. – Fried Rice Oct 21 '11 at 22:11
  • This doesn't work if the user reaches a new line naturally (without pressing return). – Declan McKenna Jun 18 '13 at 14:28
  • Deco, https://www.google.com/search?q=define%3A+newline&pws=0&hl=en. These are not 'reached naturally' AFAIK.. – Wolfert Jun 19 '13 at 08:00
  • This answer doesn't take into account many situations such as the user moving the caret or the user doing any sort of cut, copy, or paste. – rmaddy Oct 01 '15 at 14:08
0

You could try looking at the following UITextInput Protocol (which the UITextView conforms to) methods

- (NSInteger)characterOffsetOfPosition:(UITextPosition *)position withinRange:(UITextRange *)range

- (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction

- (CGRect)firstRectForRange:(UITextRange *)range

@property(nonatomic, readonly) UITextPosition *endOfDocument
jbat100
  • 16,757
  • 4
  • 45
  • 70