Search code examples
iosuiviewuiscrollviewautolayout

Setting the content size of a view inside UIScrollView


I have to lay out a few views in a View Controller which should look like this when run.

enter image description here

Initially the white view should be partially covering the blue view at the bottom like shown in the image. The blue view should stay put while the white view at the bottom can be scrolled over the blue view.

I added the blue view to the main UIView of the view controller. Then added a UIScrollView on top of blue view and added the white view on to the scroll view.

Now I'm getting the dreaded ambigeous content size error. I have pinned the scrollview on all four sides. Then added leading, bottom and trailing constraints to the white view. Then I tried adding a top constraint to the white view but the error still persisted. I also adding a height constraint to the white view to no avail.

It might be dofficult to imagine my setup so I added a demo project here as well.


Solution

  • I set the constraints for you here.

    Explanation: You are getting ambigous content size because your scrollView does not know its content (white view's) width and height.

    I added top,width and height constraint to white view. This way your scrollView knows its content width and will scroll only vertically. As for content height - u can change heightContstrait's constant in code, or completely remove height constraint if you use autolayout properly for white view's subviews.