Autoresize UITextView and UIScrollView

dennis3484 picture dennis3484 · Jan 27, 2010 · Viewed 13.8k times · Source

I already did several searches on Stack Overflow and Google, but I couldn't find a solution to my problem.

I have a Detail View for a product that includes a UIScrollView and a few subviews (UIImageView, UILabel, UITextView). You can find an example here.

First I wanna autoresize the UITextView (not the text itself!) to the corresponding height. Then I wanna autoresize the entire UIScrollView so that it fits the height of my UITextView and the elements above it. I've tried the following code:

myUITextView.frame = CGRectMake(2.0, 98.0, 316.0, self.view.bounds.size.height);

[scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:NO];
scrollView.contentSize = CGSizeMake(320.0, 98.0 + [myUITextView frame].size.height);

[self.view addSubview:scrollView];

98.0 + [myUITextView frame].size.height) because my thought was: After getting the height of myUITextView, add the height of the other subviews (98.0) to it.

Unfortunately it doesn't work very well. Depending on the content of the UIScrollView, it is too short or too long. I did some logging with the result that the height of the UITextView is always the same:

2010-01-27 14:15:45.096 myApp[1362:207] [myUITextView frame].size.height: 367.000000

Thanks!

Answer

Ronnie Liew picture Ronnie Liew · Mar 21, 2010

There is actually a very easy way to do resize the UITextView to its correct height using its contentSize.

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

One thing to note is that the correct contentSize is only available after the UITextView has been added to the view with addSubview. Prior to that it is equal to frame.size