Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoresize UITextView and UIScrollView

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!

like image 204
dennis3484 Avatar asked Jan 27 '10 13:01

dennis3484


People also ask

What is UITextView?

UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document. This class supports multiple text styles through use of the attributedText property.

Is UITextView scrollable?

if you always want it to bounce, just check the "Always bounce...", it isn't scrollable but you can move it in each direction.

How to use ScrollView in iOS?

To make the ScrollView, scrollable, we need to change the ViewController size from fixed to freeform and define some vertical spacing among the views. Set up the auto-layout rules for the ScrollView, ContentView, UIviews, and the submit button.


1 Answers

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

like image 151
Ronnie Liew Avatar answered Sep 30 '22 17:09

Ronnie Liew