Gusev Andrey
Gusev Andrey

Reputation: 456

Iphone SDK UITextView text length

How can I know that the text is out of fit (that the text is need to be scrolled)? Does it have any methods or something to do this?

Thanks.

Upvotes: 0

Views: 1814

Answers (1)

viggio24
viggio24

Reputation: 12366

Use the NSString UIKit additions. They allow to calculate the height of a string given the size and font. So you can calculate the height in this way:


CGFloat textViewWidth = CGRectGetWidth(textView.bounds);
CGSize inset = CGSizeMake(5.0,5.0);
CGSize stringSize = [myString sizeWithFont:textView.font constrainedToSize:CGSizeMake(textViewWidth-2*inset.width,1024) lineBreakMode:UILineBreakModeWordWrap];
BOOL textOutOfFit = stringSize.height+2*inset.height>CGRectGetHeight(textView.bounds);

Note that this code requires some fine tuning. Infact text inside text views has some internal margin (that I took into account using the inset structure), so the required text view height will be higher than the calculated string height. What this code does is to ask NSString to calculate its size when horizontally constrained in the textview boundaries (while 1024 in the height is the maximum UIView height possible). Then what I do is to check if the returned string height is inside or not the text view boundaries.

Upvotes: 2

Related Questions