Keeping User-Input UITextVIew Content Constrained to Its Own Frame

Posted by siglesias on Stack Overflow See other posts from Stack Overflow or by siglesias
Published on 2011-02-06T07:44:06Z Indexed on 2011/02/08 7:25 UTC
Read the original article Hit count: 181

Trying to create a large textbox of fixed size.

This problem is very similar to the 140 character constraint problem, but instead of stopping typing at 140 characters, I want to stop typing when the edge of the textView's frame is reached, instead of extending below into the abyss. Here is what I've got for the delegate method. Seems to always be off by a little bit. Any thoughts?

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    BOOL edgeBump = NO;
    CGSize constraint = textView.frame.size;

    CGSize size = [[textView.text stringByAppendingString:text] sizeWithFont:textView.font 
                                                           constrainedToSize:constraint 
                                                               lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = size.height;

    if (height > textView.frame.size.height) {
        edgeBump = YES;
    }

    if([text isEqualToString:@"\b"]){
        return YES;
    } else if(edgeBump){
        NSLog(@"EDGEBUMP!");
        return NO;
    }   

    return YES;
}

EDIT: As per Max's suggestion below, here is the code that works:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    CGSize constraint = textView.frame.size;

    NSString *whatWasThereBefore = textView.text;

    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:text];

    if (textView.contentSize.height >= constraint.height) {
        textView.text = whatWasThereBefore;
    }

    return NO;
}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c