iosstoryboardautolayoutios-universal-app

Universal Autolayout for Scrollview & UI components


I know auto layout but I am new to universal application with auto layout. I am having problem setting up Constrain to this below image.

Can you tell me how do I set auto layout for Universal App? I tried with constrain to margin & pin the leading,top,trailing space to container but it does not work.


Solution

  • Actually, autolayout works different inside a scrollview than in other views. Inside a scroll view, the leading, trailing, top and bottom constraints form a superview to the container view (scrollview in this case) defines not spacing, but sort of "how much my scroll view should scroll to the left, right, top and bottom of this component".

    So, to use autolayout in a scroll view, you must do some tricky things:

    1. Set leading, trailing, top and bottom constraints from your Scrollview to your view

    enter image description here

    1. Add a subview to the scrollview, that you'll use as a guide view. Since scrollview width changes from device to device, you need a view that have a relationship with the width of the scrollview, so you can set your constraints related to that view instead of the scrollview's left and right borders (since this will define not the size, but "how much your scrollview scrolls to left or right"). This view have a height = 0, is located in 0,0, and have the same width as the scrollview.

    enter image description here enter image description here

    1. Set constraints for that view. Height = 0. Leading space to container, and Trailing space to container set to 0 (this tells your scrollview not to scroll to the sides of your guide view). Add a top constraint to the scrollview too, since your guide view will be at the top of the scrollview. Also add a Equal width relationship between your scrollview and your guide view (this is very important, it will force your guide view to have the same width as the scrollview, hence no horizontal scroll will be available). Note that at this point, your scrollview knows how much it must scroll to the left, right, and top, but not to the bottom, so you'll see an error in the autolayout.

    enter image description here

    1. Now you build your UI, considering that the top, left and right relationships must be put in relationship to the guide view, NOT to the scrollview (you want to define spacing, not "amount of scroll"). It's hard to put all constraints needed here, so I created an example project on github: Download it here

    When you open the project, please note that all constraints between an object and the scrollview doesn't reflect spacing (as I said) but reflects how much your scrollview should scroll away from the component.

    Hope this helps,