Search code examples
xcodeconstraintsscrollviewstackview

ScrollView with embedded StackView issue


I have a scrollView with a stackView placed in it. The scrollView is constrained to the rootview. The stack view will show a xib view.

The xib views are all different lengths. The xib views are labeled simpleVC0 and simpleVC1. The length of the simpleVC0is 2500 and the length of simpleVC1 is 1000.

My problem is that when the xib views are presented in the stack view the length of the scrollView does not change to the length of the presented xib view. It is like the xib view is presented but the scroll view is locked at a specific length.

Here is simpleVC0 xib view. followed by it when run. When I try to scroll it doesn't allow me to scroll to the bottom of the xib view. it seems to cut the xib view off at a certain length. Am right in saying that this is possibly an issue that may have to be resolved in code? or can it it solved souled by the constraints. I have tried auto layout constraints however they have not worked.

enter image description here

enter image description here An example of how far down i can scroll (note the xib view is cut off as it only shows a certain amount of green.) enter image description here

enter image description here

I have constrained the scrollView to the rootview on all four sides. When the root view is loaded the xibs are established using the following code:

    //Different subViews for ingredients and steps
    if counter == 0 {
        simpleViewX = SimpleVC0().view
        simpleViewY = SimpleVC1().view
        stack.addArrangedSubview(simpleViewX)
        stack.addArrangedSubview(simpleViewY)
    }

The views are the hidden shown by changing the value of the segmented view controller. Shown below:

    @IBAction func tabselected(_ sender: Any) {
    switch (sender as AnyObject).selectedSegmentIndex {
    case 0:
        simpleViewY.isHidden = true
        simpleViewX.isHidden = false

        break
    case 1:
        simpleViewX.isHidden = true
        simpleViewY.isHidden = false

        break
    case 2:
        //calledvideo in array is the value of the counter.
        calledVideo = vids[counter]
        geturl()
        break
    default:
        break
    }
    }

Solution

  • To use a UIStackView with a UIScrollView you need to allow the stack view to expand its height based on its content.

    When laying it out in storyboard, give the stack view a height constraint (to satisfy IB's requirements), but give that height constraint a low Priority.

    Then, when adding arranged subviews, the stack view will grow vertically.

    Here's a complete example, based on the images you've shown: https://github.com/DonMag/XIBsInScrollView