3

I am trying to make a view containing an UIScrollView. This UIScrollView contains 3 UIViews. The last one contains another UIStackView I wanted to fill at runtime.

Here an image of the storyboard :

Storyboard

enter image description here

But when I add content at runtime in the second UIStackView, the ScrollView's height remains the same.

The second UIStackView is defined as the first one with:

  • Axis : vertical
  • Alignment : Fill
  • Distribution : Equal Spacing

Then I use :

mStackView.addArrangedSubview(matProgress)

The result below :

enter image description here

What's the way to have the bottom view and the ScrollView stretch to fit the content.

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
Mory
  • 198
  • 9
  • Do you initially show this with *empty* bottom view? Or when it is first shown it has *some* of the multiple-lines? – DonMag May 12 '17 at 16:27
  • When it first shown it already has some views. The problem I had is described in my comment in the accepted answer – Mory May 15 '17 at 08:24

2 Answers2

2

The layout can be done with auto-layout and constraints.

The key points are:

  • do not set height constraints on either StackView
  • set the "Main" StackView Distribution to Equal Spacing
  • set the "Main" StackView Leading, Trailing, Top and Bottom constraints to its Superview (which is the ScrollView)
  • you do need to also set a width constraint on the "Main" StackView to control the horizontal contentSize

The only quirk will be on startup. If you have NO content in the bottom / inner StackView, it will still "exist" in the Main StackView and take up space. There is a trick to get around that, but it must be done in code.

You can see a working example here: https://github.com/DonMag/StackyScrolly

DonMag
  • 69,424
  • 5
  • 50
  • 86
  • Thanks DonMag, the example you provide helped me to make it work. My project was working exactly as yours when I use `UILabels` as you've done. So the problem was that the views I added in the bottom `UIStackView` haven't got any height constraint... – Mory May 15 '17 at 07:43
0

If you have UIScrollView and the child views with auto-layout. Setting programmatically the height of the scrollview will stretch the inside views to comply with the auto-layout.

So, you get by code the height of the third view and set the UIScrollView height to view1.height + view2.height + expectedThirdViewHeight.

Jose Tomas
  • 107
  • 2
  • 8