Lijith Vipin
Lijith Vipin

Reputation: 1906

How get UITextView contentView height, if iam using sizeToFit property?

How get UITextView contentView height, if Iam using sizeToFit property ?

Upvotes: 2

Views: 254

Answers (2)

Ashish
Ashish

Reputation: 3137

UITextView itself has a function called sizeThatFits: which will return the smallest size needed to display all contents of the UITextView inside a bounding box, that you can specify.

The following will work equally for both iOS 7 and older versions and as of right now does not include any methods, that are deprecated.

- (CGFloat)textViewHeightForAttributedText: (NSAttributedString*)text andWidth: (CGFloat)width {
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText : text];
CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}

Reference link UITableViewCell with UITextView height in iOS 7?

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27428

if you are using,

 int numLines = txtview.contentSize.height / txtview.font.lineHeight;

to get the number of lines in the textView then you don't need sizeToFit or not required to set textView's frame as per content size.

txtview.contentSize.height will give you content view's height and you can get number of lines.

But make sure that you are doing this in viewDidAppear(or any where after your view is appeared) not in viewDidload because in viewDidload your textview is not loaded completely.

Upvotes: 2

Related Questions