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).

2 answers

  • answered 2019-05-20 15:24 NRitH

    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

  • answered 2019-05-20 16:30 RajeshKumar R

    For scrollview add Top, Leading, Trailing, Bottom constraints to its superview with 0 constant.

    For ContentView add Top, Leading, Trailing, Bottom constraints to its superview scrollview with 0 constant. And add equal width to the scrollview, then add equal height to the scrollview with priority 999.

    Now add Top, Leading, Trailing, Bottom constraints for the subviewA, subviewB, subviewC views.

    Then add Top, Leading, Trailing, Bottom, height constraints to the subviews of subviewA, subviewB, subviewC views.