I have a UIStackView
in storyboard like this:
@IBOutlet weak var stackView: UIStackView!
I want to be able to add views to this UIStackView
programmatically like this:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.backgroundColor = .gray
stackView.addArrangedSubview(view)
Initially, the views added will be 50×50 in dimensions. When only a few are added, I want them to stay 50×50 and be centered in the screen.
But when you add more than there is width on the screen, I want them to shrink in size.
Here is what I want it to look like. The first row is with three 50×50 views added. The next row has more added and notice how they shrink in width to fit the width of the screen:
Is this possible with a UIStackView
and adding views programmatically like this?
2
Answers
Yes, It’s possible.
You can set set the following thing:
Constraints:
StackView Properties:
Code:
Now, add subviews programmatically.
This can be done with auto layout constraints only… no need to "calculate" sizing.
Start with a stack view:
UIStackView
Distribution: Fill Equally
50
greaterThanOrEqualTo
view leading plus 8-points ("side padding")lessThanOrEqualTo
view trailing minus 8-points ("side padding")Every time you add an arranged subview, give it a
Width
constraint of50
— but with aPriority
of.defaultHigh
.That tells auto layout: *"TRY to make the view 50-points wide. If you can’t, then use the next auto layout command for its width." In this case, the "next" command will be the stack view’s
Fill Equally
property.Here’s some quick example code. A stack view near the top, starting with one subview… along with "Add" and "Remove" buttons:
Looks like this: