Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView height while adding content programmatically in UIStackView

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.

like image 885
Mory Avatar asked Jan 31 '26 14:01

Mory


1 Answers

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

like image 169
DonMag Avatar answered Feb 02 '26 04:02

DonMag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!