Fogmeister
Fogmeister

Reputation: 77661

Adding padding to the beginning and end of a UIStackView

I've been switching over to UIStackView recently and trying to do all my layout with it and it's so much easier than using Auto Layout... with one exception.

I have a layout using nested UIStackViews with a vertical stack view and inside it is a horizontal stack view.

Like this...

|    Label    |
|    Label    |
|Button Button|
|    Label    |

This is fine except I now want to have a space between the buttons and the edges of the screen. I can set a space between the buttons but not at the edges.

Is there a way to do this?

What I would like is this...

|   B     B   |

The buttons both have a background colour with rounded corners. I'd like a gap between the edge of the screen and the background.

If that makes sense.

I just can't find anything that would allow me to do this.

Upvotes: 7

Views: 11088

Answers (2)

Mazen K
Mazen K

Reputation: 3672

StackView doesn't have padding attribute as of iOS 14 / Xcode 12. But we could set the layout margin.

  • through Interface Builder:

enter image description here


OR

  • through code, could configure the stack view to lay out its arranged subviews relative to its layout margins:

stackView.isLayoutMarginsRelativeArrangement = true

For iOS > 10

stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)

For iOS <= 10

stackView.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)


P.S drawback of this approach, when the StackView has no subviews, it would persist its layout margins. Therefore to remove the paddings we should set a layout margin with zero edge insets through code.

Upvotes: 17

Zolt&#225;n Mat&#243;k
Zolt&#225;n Mat&#243;k

Reputation: 4045

I realize this is a super old question, but you can do it like this:

  • add 0px wide UIViews to both sides of the horizontal stack view
  • set their background color to clearColor
  • set the horizontal stack view's Distribution to Equal Spacing.

[Update: I just saw you mentioned this in the comments]

Upvotes: 0

Related Questions