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!

3
  • Possible duplicate of stackoverflow.com/questions/5225763/… and stackoverflow.com/questions/411398/… Commented Oct 21, 2011 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? Commented Oct 21, 2011 at 14:17
  • +1 for this question, he said he tried something :) Commented Sep 18, 2013 at 5:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
This doesn't work if the user reaches a new line naturally (without pressing return).
Deco, google.com/search?q=define%3A+newline&pws=0&hl=en. These are not 'reached naturally' AFAIK..
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.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.