Showing posts with label number of lines. Show all posts
Showing posts with label number of lines. Show all posts

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;
}