Get Number of Lines in UItextView

1.3k views Asked by At

I am trying to build an app that supports variable size text box depending on the content. The size of the UITextView should increase up to 4 lines and then activate the scrolling.

I am not able to get the number of lines when the text is being entered.

Please suggest me some way to do that. Any sample code snippet would be highly appreciated.

Thanks in advance!!

1

There are 1 answers

0
devsri On BEST ANSWER

I tried one temporary solution to this problem. One can add the following piece of code in - (void)textViewDidChange:(UITextView *)textView method of your view controller and change the delegate to the file owner in IB.

    float adjustvar;
    if ([textView.text isEqualToString:@""]) {
        //change these values according to your requirement as they are hard coded to adjust cursor and size of the textview
        adjustvar = 37.0;
        textView.contentInset = UIEdgeInsetsMake(6 ,0 ,0 ,0);
    }
    else {
        adjustvar = textView.contentSize.height;
    }

    CGRect temp = textView.frame;
    temp.origin.y = textView.frame.origin.y + textView.frame.size.height - adjustvar;
    temp.size.height = adjustvar;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.4];
    [UIView setAnimationsEnabled:YES];

    if (temp.size.height > 142.0) {
        textView.scrollEnabled = YES;
    }
    else {
        textView.scrollEnabled = NO;
        textView.frame = temp;
    }

    [UIView commitAnimations];`

Hope this helps. If any better solutions kindly help out.

Thanks