Text Limit in UITextView

I am trying to restrict text input in a UITextView in cocoa -touch. I really want to limit the number of lines, not the number of characters. So far I have this to count the number of rows:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if([text isEqualToString:@"\n"]) { rows++; } NSLog(@"Rows: %i", rows); return YES; } 

However, this does not work if the line is automatically wrapped, and not the user, by pressing the return key. Is there a way to check if the text was wrapped like checking for "\ n"?

Thank.

+5
cocoa-touch
Jan 04 '09 at 17:59
source share
1 answer

Unfortunately, using NSString -stringWithFont: forWidth: lineBreakMode: does not work - which wrapper mode you choose, the text wraps around a width that is less than the current width, and the height becomes 0 on any overflow lines. To get the real number, set the line to a frame that is higher than the one you need, then you will get a height that is greater than your actual height.

Pay attention to my fiction in this (subtracting 15 from the width). This may be due to my views (I have one in the other), so you may not need it.

 - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText { NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText]; // TODO - find out why the size of the string is smaller than the actual width, so that you get extra, wrapped characters unless you take something off CGSize tallerSize = CGSizeMake(aTextView.frame.size.width-15,aTextView.frame.size.height*2); // pretend there more vertical space to get that extra line to check on CGSize newSize = [newText sizeWithFont:aTextView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; if (newSize.height > aTextView.frame.size.height) { [myAppDelegate beep]; return NO; } else return YES; } 
+14
Apr 08 '09 at 6:10
source share



All Articles