Alan Waterman
Alan Waterman

Reputation: 9

Auto size horizontal UIStackView width based on variable number of buttons?

I have a UIStackView in which I programmatically add buttons based on the available actions for some content. I'd like the stackview to grow horizontally as each button is added and each button to be only the width needed to contain the text.

Where I'm at now, all buttons are sized to their text in the stackview and the first button takes the remainder of the stackview width as layed out.

What I'd like to do is have the stackview size in width dynamically based on the buttons added and how wide each button is.

This is what I have now:

Horizontal stackview with three buttons

Upvotes: 0

Views: 932

Answers (1)

DonMag
DonMag

Reputation: 77477

Give your stack view these properties:

enter image description here

Constrain the Top of the stack view, and constrain it Centered Horizontally:

enter image description here

As you add buttons, its width will expand to fit the buttons, and it will remain horizontally centered:

enter image description here


Edit

And, if you want the stack view to expand left-to-right, constrain the stack view's Leading instead of centered:

enter image description here

Upvotes: 0

Related Questions