32

I have two items in a vertical UIStackView: a UILabel and a UITableView. When a dynamic amount of UITableViewCells get added to the UITableView at runtime, the UIStackView does not get larger.

Is there a general way to increase the size of the UIStackView?

jshapy8
  • 1,983
  • 7
  • 30
  • 60

4 Answers4

29

You should call sizeToFit() and layoutIfNeeded() on the subviews of the stackView. Constrain the UIStackView as you normally would, and constrain the subviews as you normally would.

Also, you need to have it set to Fill Proportionally and it will resize to fit the new content.

Siriss
  • 3,737
  • 4
  • 32
  • 65
  • Call them at instantiation or each time the `UITableView` is updated? – jshapy8 Jun 30 '17 at 03:39
  • Try calling them in `viewWillLayoutSubviews` – Siriss Jun 30 '17 at 03:50
  • 2
    viewWillLayoutSubviews is a method in the UIViewController, so I don't understand the answer: "You should call sizeToFit() and layoutIfNeeded() inside viewWillLayoutSubviews on the subviews of the stackView." – Gob Aug 24 '18 at 16:18
  • Superb answer. I was facing some problem similar to this from 2 days and this suggestion saved my life. – Abhishek Khedekar Sep 14 '20 at 18:42
  • Thanks! For those interested also in better understanding distribution and alignment, check out this article: https://medium.com/better-programming/uistackview-distribution-vs-alignment-146b9612e24c – Andy Weinstein Nov 10 '20 at 10:29
  • if I to add spacing either with the `spacing` property or with constraints between elements, my last element in the stack view start to be resized, ignoring the height constraint – Mando Jul 28 '22 at 19:36
16

Make sure you don't have a bottom constraint of a height constraint on the stackview. You should only need left, right and top constraint.

NeroSeph
  • 161
  • 1
  • 3
12

I had this on iOS 12, while it was working fine on iOS 13. Just set:

stackView.distribution = .fillProportionally

Fixed it :)

Urkman
  • 1,298
  • 1
  • 16
  • 32
5

you one need to fill proportionally and it will work according to your code

Muhammad Iqbal
  • 109
  • 1
  • 9