Search code examples
iosuiscrollviewios-autolayout

ScrollView width constraint with fixed width views


I'm working on an app in XCode 10 with Swift 4. I have set up my view in storyboard for iPhone (wC, hR) in the following way:

  • Scroll View (Top: superview, Bottom: superview, Trailing: Safe area, Leading: safe area)

  • Inside the scroll view is a Container View: T,B,L,R to superview, equal width to base view (i.e. the screen)

  • Within the container view are several labels and image views.

I have no issues with this setup.

The problem is when I make adjustments for iPad (wR, hR). Here I have disabled the trailing and leading constraints and instead added a width constraint of 690 and have aligned horizontally to superview. When I do this I get a constraint error that says "Ambiguous scrollable content width".

I believe the problem is that I'm aligning horizontally in relation to the superview which is the scroll view, and thus have no reference to the base view, but I'm not sure how to adjust this so it works.


Solution

  • I think you'll need to use two "container" views.

    for iPhone (wC, hR):

    • scrollView -- Top: superview, Bottom: superview, Trailing: Safe area, Leading: safe area)
    • "SuperContainerView" subview of scrollView -- Top/Bot/Lead/Trail to scrollView (the superView), equal width to scrollView
    • "ContainerView" subview of SuperContainerView -- Top/Bot/Lead/Trail to SuperContainerView

    Constraints on the subviews of ContainerView will control ContainerView's height, which will control SuperContainerView's height, which will control scrolling.

    For iPad (wR, hR):

    • Disable the ContainerView's Leading and Trailing constraints
    • add a Width constraint of 690
    • add a CenterX constraint to SuperContainerView

    Results... Green is ContainerView, Blue is SuperContainerView (scroll view is inset 8 on each side):

    enter image description here

    enter image description here

    enter image description here

    If you want a max width of 690 when running on a phone rotated to landscape orientation, you'll need to do similar constraint modifications for wC, hC