iPhone: Limiting text input in an UITextView
I am trying to limit the am开发者_运维问答ount of LINES a user can have in an UITextView. Let's consider I only want to allow 4 lines (i.e. in the following example, you can't go higher than a height of 84 pixels with the given font in a given UITextView with a width of 200).
I coded this to achieve the limiting and it works fine:
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText {
NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];
CGSize strSize = [newText sizeWithFont:textView.font constrainedToSize:CGSizeMake(200, 10000) lineBreakMode:UILineBreakModeWordWrap];
if (strSize.height > 100)
{
return NO; // can't enter more text
}
else
return YES; // let the textView know that it should handle the inserted text
}
So far so good. The problem starts when I try to be sneaky and enter as many 'x's as I can before each return. In that case, I can get an extra of 4 lines... which I obviously do not want to allow. I assume that this has something to do with the lineBreakMode? Is there any case to alter this? I haven't found much in the docs (but then again, I usually have a hard time understanding them).
I attached a couple of screenshots to illustrate the problem. I'd be grateful for any suggestions. Thanks a lot!
(I hope I understood your problem correctly... )
If you look closely, there's a margin in UITextView
. If you use sizeWithFont:
carelessly, it can return unexpected results in special cases (because you disrespect the text view's margin).
You should either 1) adjust the width you use in sizeWithFont:
to respect the text view's margin or 2) use an auxiliary UITextView
object to accurately compute the content size.
Looks to me like word wrapping is on in UITextView and there's not much you can do to change it (please tell me I am wrong). If you want 4 lines only, maybe 4 UITextField's in a UIScrollView (sent the return key to Next). Or reduce the ContentSize when the length of the render rectangle of each line exceeds the height of one line.
See also limiting text in a uitextview
精彩评论