Search code examples
swiftios8autolayoutscrollview

Changing ScrollViews subview dynamically in iOS 8


I'm using a ScrollView in my main page to scroll vertically the content in an view like this (Ipad resolution) :

enter image description here

For this I set a View in the top and another View below.

But want I want to do here is change the View below to displays to another View more bigger if some condition is true, (e.g in the viewDidLoad()) and the ScrollView scroll vertically regarding the size of the another View, but the size of the another View it's the double of the actual , something like the following image :

enter image description here

Of course the above image only show as I like to see it in general, In this case I wish to grow the contentSize of the ScrollView to more higher (in runtime).

My problem here is that when I not set the respective constraints I'm capable to change the contentSize as I want, but when I rotate the device my subviews remains in 768 of width, but if I set the autolayout constraints when I rotate the device all work fine , but I can't update the contentSize of the ScrollView because it calculate his metrics based in his subviews.

How can I accomplish this behaviour?

There are any other UI better to this than ScrollView?


Solution

  • Here is how to set it up so that you can scroll vertically, and update the height of the grayView programmatically.

    1. Constrain the top, left, right and bottom of the scrollView to the top, left, right, and bottom of the top level view.

    2. Constrain the left, top, and right of the orangeView to the left, top, and right of the scrollView. Constrain the width of the orangeView to be equal to the width of the scrollView. Set a constraint for the height of the orangeView (say 200).

    3. Constrain the left, bottom, and right of the grayView to the left, bottom, and right of the scrollView. Constrain the width of the grayView to be equal to the width of the scrollView. Set a constraint for the height of the grayView (say 800). Make an IBOutlet to this constraint to your code so that you can update its height by changing its constant property. To do this, find the constraint in the Document Outline view and control-drag from it to your code to create the IBOutlet. Give it a name like grayViewHeight. When you want to set it do grayViewHeight.constant = 1000.

    4. Add a vertical space constraint between the orangeView and the grayView.

    Now the content size of your scrollView is fully specified and you can grow it when you need to. The orangeView and grayView will automatically stretch horizontally to match the width of the scrollView in all orientations.