Ashh
Ashh

Reputation: 569

Width of button in horizontal stackview - iOS - Storyboard

I have two controls in vertical stack views and below is my problem

I want my controls to display like this

enter image description here

Instead it displays like this

enter image description here

How can I set my button title fit so that the button's width do not increase

Also the button title is dynamic so, I dont have control to set it as constant value

Please advice

Upvotes: 3

Views: 8326

Answers (2)

DonMag
DonMag

Reputation: 77433

There are several ways to do this. While a UIStackView is not needed, it can save a few steps in setting up constraints.

So, here is one approach:

  • I've constrained my stack view 20-pts to Top, Leading and Trailing (safe-area), but no bottom or height constraints.
  • Stack view is set to Alignment: Center Distribution: Fill Spacing: 2
  • The buttons have Content Insets of 40 for Left and Right, and 4 for Top and Bottom. That will allow them to stretch / contract horizontally based on the Dynamic Titles.
  • I gave the labels a Height constraint of 28.5 (so, just a little vertical padding), and gave them Equal-Width constraints to the stack view.
  • The text field also has an Equal-Width constraint to the stack view.

enter image description here

So, the buttons stay centered and adjust their widths to the titles, and the labels and text field stretch to fit the width of the stack view.

Upvotes: 6

3Qax
3Qax

Reputation: 354

I would suggest using set content hugging priority method. If you are doing your view programmatically it should look somewhat like this:

myButton.setContentHuggingPriority(.required, for: .horizontal)

Upvotes: 2

Related Questions