2

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

Lijith Vipin
  • 1,870
  • 21
  • 29
  • If you are using sizeToFit then then don't you use `textView.frame.size.height` – Nirav D May 31 '17 at 07:18
  • @NiravD My need is to get no.of lines from UITextView. I got solution as : `int numLines = txtview.contentSize.height / txtview.font.lineHeight;`. But I can't get correct textView contentView height. – Lijith Vipin May 31 '17 at 07:21

2 Answers2

2

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.

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
1

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?

Ashish
  • 2,977
  • 1
  • 14
  • 32