Limiting text in a UITextView
Asked Answered
C

1

5

I am trying to limit the text input into a UITextView in cocoa-touch. I really want to limit the amount of rows rather than the number of characters. So far I have this to count the amount 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 doesn't work if the line is automatically wrapped rather than the user pressing the return key. Is there a way to check if the text was wrapped similar to checking for "\n"?

Thanks.

Chart answered 4/1, 2009 at 17:59 Comment(0)
C
14

Unfortunately, using NSString -stringWithFont:forWidth:lineBreakMode: doesn't work - which ever wrap mode you choose, the text wraps with a width that is less than the current width, and the height becomes 0 on any overflow lines. To get a real figure, fit the string into a frame that is taller than the one you need - then you'll get a height that is greater than your actual height.

Note my fudge in this (subtracting 15 from the width). This might be something to do with my views (I have one within another), so you might 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's 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;
}
Cover answered 8/4, 2009 at 6:10 Comment(2)
Hi Jane - I know this post is rather old, but it appears that this is a very similar problem to the one I am facing [here] (#5605726). Is this the problem you're describing here or is your solution for a slightly different problem?Milicent
In iOS 7 I found the following margins and padding values for UITextView that may be the cause you need to use "tallerSize": textContainerInset and textContainer.lineFragmentPadding. See UITextView referenceYepez

© 2022 - 2024 — McMap. All rights reserved.