Search code examples
iosautolayoutuistackview

How to use stack view to autolayout label and button?


How can I layout a label and a button inside a UIStackView in such a way that the button only takes as much space as it needs and the rest is left for the label? Button text could be various length due to localizations.

The UIStackView here is alignment: center with distribution: fill.The only missing thing here is not stretching the button beyond the width needed for text and insets.

enter image description here

It doesn't seem possible with just the distribution settings. If Fill Proportionally is set the button must have a width constrain . Tried playing with the compression and hugging to no success, maybe I am doing something wrong.

EDIT: Found out why content hugging wasn't working. It needed a value >= 761 and not higher than 250 as I thought. Because 250 is the label content hugging value. Why 761? Can't really say.


Solution

  • You need to set the Content Hugging priority of your button to something higher than 250. That way the button does not want to grow bigger than it needs to.