Limit number of lines in UITextView

佐手、 提交于 2020-01-05 04:33:11

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7850450/limit-number-of-lines-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!