Search code examples
iosswiftuistackview

Add views to UIStackView and have them shrink in width of the screen width runs out


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:

enter image description here

Is this possible with a UIStackView and adding views programmatically like this?


Solution

  • Yes, It's possible. You can set set the following thing:

    Constraints:

    1. Add some height constraint that you want.
    2. Add minimum width to stack view.
    3. Add X and Y position to stack view.

    enter image description here

    StackView Properties:

    1. Set alignment to fill.
    2. Set distribution to fill equally.
    3. Add some spacing, I've added 5. enter image description here

    Code:

    1. Take IBOutlet of stack view width in UIViewController class.
    2. Calculate width of stack view as:
    width = ({number of subviews} * {width of one subview}) + ({number of subviews - 1} * {stack view spacing added in step 3 of properties})
    
    1. Set this width to constraint of stack view when update or add remove on subviews.

    Now, add subviews programmatically.