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 50x50 in dimensions. When only a few are added, I want them to stay 50x50 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 50x50 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?
Yes, It's possible. You can set set the following thing:
Constraints:
StackView Properties:
Code:
width = ({number of subviews} * {width of one subview}) + ({number of subviews - 1} * {stack view spacing added in step 3 of properties})
Now, add subviews programmatically.