views:

320

answers:

3

Hi all,

I'm having a scrollview as the detailedview of tableview cell. There are multiple views on the detailedview like labels, buttons etc. which I'm creating through interface builder. What I'm creating through interface builder is static. I'm putting everything on a view of height 480.

A label on my detailedview is having dynamic text which can extend to any length. The problem is that I need to set the scrollview's content size for which I need its height.

How shall I set scrollview's height provided the content is dynamic?

A: 

I guess there's no auto in case of scrollview, and the contentsize should be calculated for static views on the screen at least and for dynamic once it should be calculated on the go.

neha
A: 

You could try to use the scrollview'ers ContentSize. It worked for me and I had the same problem with the control using dynamic content.

    // Calculate scroll view size
float sizeOfContent = 0;
int i;
for (i = 0; i < [myScrollView.subviews count]; i++) {
    UIView *view =[myScrollView.subviews objectAtIndex:i];
    sizeOfContent += view.frame.size.height;
    [view release];
}

// Set content size for scroll view
myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, sizeOfContent);

I do this in the method called viewWillAppear in the controller for the view that holds the scrollview. It is the last thing i do before calling the viewDidLoad on the super.

Hope it will solve your problem.

//hannes

Hannes Larsson
Thank you so much, Hannes.. I'm thinking why this didn't strike me..
neha
You release the views you iterate through, which removes them from the scrollview. Couldn't paste code properly in the comment, added as answer instead.
Henrik Erlandsson
+1  A: 

Correct shorter example:

float hgt=0; for (UIView *view in scrollView1.subviews) hgt+=view.frame.size.height;

[scrollView1 setContentSize:CGSizeMake(scrollView1.frame.size.width,hgt)];

Note that this only sums heights, e.g. if there are two subviews side by side their heights with both be added, making the sum greater than it should be. Also, if there are vertical gaps between the subviews, the sum will be less than it should be. Wrong height confuses scrollRectToVisible, giving random scroll positions :)

This loop is working and tested:

float thisy,maxy=0;for (UIView *view in scrollView1.subviews) {
    thisy=view.frame.origin.y+view.frame.size.height; maxy=(thisy>maxy) ? thisy : maxy;
}
Henrik Erlandsson
Thanx Henrik, this' really helpful! As I can't accept two answers, I'll upvote yours.. :)
neha