Tuesday, June 5, 2012

Limit the number of lines in UITextView




- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    
    // limit the number of lines in textview
    NSString* newText = [mytextView.text stringByReplacingCharactersInRange:range withString:text];

    // pretend there's more vertical space to get that extra line to check on
    CGSize tallerSize = CGSizeMake(mytextView.frame.size.width-15, mytextView.frame.size.height*2); 

    CGSize newSize = [newText sizeWithFont:mytextView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
    
    if (newSize.height > mytextView.frame.size.height)
    {
        NSLog(@"two lines are full");
        return NO;
    }
    
    
    // dismiss keyboard and send comment
    if([text isEqualToString:@"\n"]) {
        [mytextView resignFirstResponder];
        
        return NO;
    }
    
    return YES;
}

1 comment:

  1. much more easier is to do like:

    Swift:

    textView.textContainer.maximumNumberOfLines = 10;
    textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;

    Obj-C:

    textView.textContainer.maximumNumberOfLines = 10;
    [textView.layoutManager textContainerChangedGeometry:textView.textContainer];

    ReplyDelete