3

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

Ashh
  • 569
  • 1
  • 6
  • 28
  • That doesn't look like a good use of a stack view. – matt Jan 30 '19 at 23:38
  • if I have two controls like i mentioned, you are right..but I have around 5 rows and i wanted each alternating row to look like the pic..button, label, label, button, textfield..that's my actual hierarchy so I started with vertical stackview – Ashh Jan 30 '19 at 23:42
  • 2
    I'm still not persuaded a stack view is needed. A stack view is for setting up spacing between views, e.g. if you wanted to ensure equal spacing between all your views to cover the height of the screen. But if all you have is one view on top of another on top of another, touching, you don't need a stack view. Just align their centers and set up the constraints between them, yourself. – matt Jan 31 '19 at 00:55

2 Answers2

6

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.

DonMag
  • 69,424
  • 5
  • 50
  • 86
1

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)
3Qax
  • 324
  • 1
  • 2
  • 12
  • 1
    but my label also gets shrunken – Ashh Jan 31 '19 at 01:53
  • First of all why didn’t you mention it originally in question? If your label shrunk itself so that content appears to not be completely displayed try setting it’s compression resistance like: `myLabel.setContentCompressionResistancePriority(.required, for: .vertical` – 3Qax Jan 31 '19 at 02:21
  • Sorry..i thought u could understand from picture i added – Ashh Jan 31 '19 at 02:25
  • And maybe try setting numberOfLines of label to 0 – 3Qax Jan 31 '19 at 02:28