How do I auto size a UIScrollView to fit its content

jwerre picture jwerre · May 31, 2010 · Viewed 168.6k times · Source

Is there a way to make a UIScrollView auto-adjust to the height (or width) of the content it's scrolling?

Something like:

[scrollView setContentSize:(CGSizeMake(320, content.height))];

Answer

leviathan picture leviathan · Jun 24, 2013

The best method I've ever come across to update the content size of a UIScrollView based on its contained subviews:

Objective-C

CGRect contentRect = CGRectZero;

for (UIView *view in self.scrollView.subviews) {
    contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;

Swift

let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
    rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size