Search code examples
iosswiftuiscrollviewautolayout

Handling UIView/UIScrollView With Unknown Size (AutoLayout/Swift)


I have a view in my app that is structured like so;

  • UIViewController (self)
    • UIView (self.view)
      • UIScrollView (scrollView)
        • UIView (contentView)
          • UIView (subviewA)
          • UIView (subviewB)
          • UIView (subviewC)

After reading a variety of posts on UIScrollView (see here and here), I now have a UIScrollView that looks properly, but doesn't actually scroll. I believe this is because my three subviews (subviewA, subviewB, and subviewC) are all built with AutoLayout.

My contentView has a bottom constraint of contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

Ideally, I'd like my contentView's bottom anchor to actually be at the bottom of subviewC, but since subviewC is built with AutoLayout, it doesn't have a defined size when it is added to to contentView, and thus, the scrollView doesn't actually scroll.

Can anyone advise why my scroll does does not scroll vertically? It does appear that the subviews are all being added, but the lowest subview is well off-screen and doesn't actually allow me to scroll.

(There's a little bit more to this, such as how I'd like contentView to have a border that surrounds subviewA, subviewB, and subviewC, but I feel resolving the scroll issue will probably lead me down the right path on that).


Solution

  • A scroll view has to be able to calculate the size of its contents, so yes, your contentView's top constraint should match subviewA's top, and contentView's bottom should match subviewC's bottom. It's perfectly fine that all the subviews use constraints, as long as the subviews' tops and bottoms are constrained.

    Once your contentView is constrained to its subviews, constrain all 4 of its edges to the scrollView's edges. (If you don't want it to scroll horizontally, then also constrain the contentView's width to be equal to the scrollView's.)

    enter image description here