Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SizeToFit on a UIScrollView's content size

Tags:

A UIView has a SizeToFit method that will make the UIView fit all of it's subviews. Is there anything like that, which will just return the size that it calculates and not modify any view's frame.

I have several subviews on a UIScrollView and I want to do SizeToFit on the scroll view's contentSize, rather than it's frame. I have to do it on the contentSize, because I don't want to increase the "real" size of the UIScrollView, and the content is loaded dynamically and asynchronously so I can't do it manually when I add the subviews to the UIScrollView.

like image 648
Jonathan. Avatar asked Oct 25 '10 20:10

Jonathan.


2 Answers

At the moment, this is the best I have:

CGRect contentRect = CGRectZero;
for (UIView *view in self.subviews)
    contentRect = CGRectUnion(contentRect, view.frame);
self.contentSize = contentRect.size;
like image 105
William Jockusch Avatar answered Sep 20 '22 15:09

William Jockusch


If your function is called frequently, you wouldn't want to iterate over the subviews each time. Instead, whenever a subview is added, do a union of the current contentSize and the frame of the new subview.

- (void)didAddSubview:(UIView *)subview {
    CGRect tmp;
    tmp.origin = CGPointZero;
    tmp.size = self.contentSize;
    tmp = CGRectUnion(tmp,subview.frame);
    self.contentSize = tmp.size;
}
like image 34
ughoavgfhw Avatar answered Sep 19 '22 15:09

ughoavgfhw