问题
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