Stack

In practice, I usually find that using a UITableView makes most sense for displaying scrollable content in an app, however every now and again it is handy to use a UIScrollView + UIStackView. The problem is: it occurs infrequently enough that I cannot recall how to set up the constraints! So here’s my notes for my future reference, and hopefully yours too :)

Here’s a screenshot of how to set it up in Xcode: (click to zoom)

Xcode

Theory

  • The frame layout guide and content layout guides are only to be used for child views of the scroll, and the child views are to be (usually) only constrained to these guides.
  • The frame layout guide is for setting child view’s sizes to match the scroll’s visual size.
  • The content layout guide is what defines the scroll view’s content size.

Vertical scroll setup

  • Make a UIScrollView and constrain it normally to define its size (eg not using its layout guides).
  • Put a vertical UIStackView inside the UIScrollView.
  • Constrain the stack’s leading/trailing/top/bottom to the scroll’s content layout guide.
  • Make the stack’s width equal to the scroll’s frame layout guide.
  • Put views in the stack. These views don’t need any constraints put on them at all.

Horizontal scroll setup

  • Make a UIScrollView and constrain it normally to define its size (eg not using its layout guides).
  • Put a horizontal UIStackView inside the UIScrollView.
  • Constrain the stack’s leading/trailing/top/bottom to the scroll’s content layout guide.
  • Make the stack’s height equal to the scroll’s frame layout guide.
  • Put views in the stack. These views don’t need any constraints put on them at all.

Paged scroll setup

If you want each child of the stack to be a whole ‘page’:

  • Horizontal scrolling: Constrain the stack’s childrens’ width to equal the scroll’s frame layout guide.
  • Vertical scrolling: Constrain the stack’s children’ height to equal the scroll’s frame layout guide.
  • Set ‘isPagingEnabled’ to true on the scroll.

Thanks for reading, I hope this is helpful, God bless :)

Photo by Fernando Andrade on Unsplash

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

iOS Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin



 Subscribe via RSS