In my project I have a simple UIView with a UIScrollView subview. I am trying to calculate the height based on the content within the UIScrollView with the following code:

file.h
@interface ScrollViewController : UIViewController {
IBOutlet UILabel* topLabel;
IBOutlet UILabel* bottomLabel;
IBOutlet UIScrollView * scroller;
}
@property(nonatomic,retain) IBOutlet UIScrollView *scroller;
file.m
- (void)viewDidLoad {
[scroller setScrollEnabled:YES];
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in scroller.subviews)
{
scrollViewHeight += view.frame.size.height;
}
// print value 88.000000
NSLog(@"%f", scrollViewHeight);
[scroller setContentSize:CGSizeMake(320, scrollViewHeight)];
[super viewDidLoad];
}
I don’t know why the code doesn’t work.
Well, a couple things. First, set a breakpoint at the beginning of that method and walk through your code one line at a time to see what it’s doing.
Second, Depending on how your views are laid out, especially if you have views next to each other, that code might not work. It’ll also not work if there is vertical margin/space in between the subviews. Instead, you might try this code when looping through the subviews:
This should get you the correct height.