152

This is my setup: I have an UIScrollView with leading,top, trialing edge set to 0. Inside this I add an UIStackView with this constraints:

stackView.centerYAnchor.constraintEqualToAnchor(selectedContactsScrollView.centerYAnchor).active = true  
stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor).active = true

Inside the stack view I add some views.
My issue is that because of the constraints the first view added to stack view will also have leading edge = 0.

What are the ways that I could add some padding to the first view ? Without adjusting the scroll view constraints.

Adrian
  • 16,820
  • 32
  • 99
  • 188
  • 3
    would you mine changing the accepted answer? Tolga's answer seems much better. – Honey Aug 27 '19 at 20:11
  • Please don't change the accepted answer. The accepted answer is much better. Tolga's answer does not state when to do these settings, does not take safeAreaLayoutMargins into account, and does not use the standard layout margin sizes. And it is not clear how to change the answer to do this properly. – fishinear Aug 16 '20 at 12:42

12 Answers12

427

When isLayoutMarginsRelativeArrangement property is true, the stack view will layout its arranged views relative to its layout margins.

stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
stackView.isLayoutMarginsRelativeArrangement = true

But it affects all arranged views inside to the stack view. If you want this padding for only one arranged view, you need to use nested UIStackView

Tolga Okur
  • 5,293
  • 2
  • 17
  • 17
  • 2
    `isLayoutMarginsRelativeArrangement` is a getter, setter is `layoutMarginsRelativeArrangement`. I can't edit the answer – maross Mar 31 '17 at 09:59
  • 6
    @maross there is no difference between getter and setter function in Swift. But you are right, people who develop with Objective-C should use `layoutMarginsRelativeArrangement` instead. Official documentation: https://developer.apple.com/reference/uikit/uistackview/1616220-islayoutmarginsrelativearrangeme – Tolga Okur Apr 13 '17 at 07:15
  • 3
    For Objective-C: `stackView.layoutMargins = UIEdgeInsetsMake(0, 20, 0, 20); [stackView setLayoutMarginsRelativeArrangement:YES];` – Snouto Nov 27 '17 at 00:58
  • 4
    _Feb 2019, at midnight sitting at the office_ - Answers like these give me the strength to move forward. Thanks @tolpp – nefarianblack Feb 09 '19 at 18:09
  • Great solution! Thanks! – Pedro Trujillo Mar 26 '21 at 22:24
  • true solution. thank you. – Vadim Kurochkin Mar 28 '21 at 14:37
173

I have found that constraints don't work inside a Stack View, or they seem somewhat strange.

(Such as if I add leading/trailing constraint to selected on image stackview, that adds leading to collectionview too, but doesn't add trailing; and it be conflict for sure).

stackview inside stackview

To set layout margins for all views inside the stackview, select:

Stack View > Size Inspector > Layout Margins > Fixed

Note: "Fixed" option was formerly called "Explicit", as seen in the screenshots.

Then add your padding:

storyboard

pkamb
  • 26,648
  • 20
  • 124
  • 157
Zaporozhchenko Oleksandr
  • 3,802
  • 3
  • 18
  • 36
  • 30
    one of the things Apple hide. I hate how Xcode is the opposite of good, friendly and easy. Thanks – Duck Nov 14 '16 at 14:32
  • Xcode keeps on crashing when I change those explicit layout margins. Filed a bug but they replied it was a duplicate. – mvandillen Mar 03 '17 at 14:48
  • That's what I couldn't find in the UI. Change Layout Margins to Explicit to see the fields for Stack View margins. – pkamb Jun 20 '17 at 19:32
  • 14
    FYI XCode 9 now calls this "Fixed" instead of "Explicit". – Mel Sep 13 '17 at 01:30
  • Also in Xcode 9, uncheck "Use Safe Area Layout Guides" in File inspector, which as of writing still causes a lot of problems in IB, and stick with normal Layout guides for your constraints. – PJ_Finnegan Oct 25 '17 at 12:56
31

The solution you have provided doesn't add a padding for your views inside your UIStackView (as you wanted in the question), but it adds a leading for the UIStackView.

A solution could be to add another UIStackView inside your original UIStackView and give the leading to this new UIStackVIew. Then, add your views to this new UIStackView.

Hint, you can do that completely using Interface Builder. In other words, no need to write code for it.

William Kinaan
  • 25,507
  • 20
  • 76
  • 115
19

What worked for me is to add to stack view another UIView that's just a spacer (works at least with stackView.distribution = .Fill):

let spacerView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
stackView.addArrangedSubview(spacerView)
stackView.addArrangedSubview(viewThatNeedsSpaceBeforeIt)
stackView.addArrangedSubview(NextView)...
dorsz
  • 725
  • 8
  • 16
6

If you only need leading padding, then you can set the stack view's Alignment to "Trailing" and then you will be free to specify unique Leading constraints on each of its contained subviews.

As a bonus, you can also set the stack view's alignment to "Center" and then you can use Leading and/or Trailing constraints to give each item its own padding on both sides.

6

swift 3: You just need set offset by:

firstView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 200).isActive = true

Be sure this constraint set after you parentView.addArrangdSubView(firstView)

William Hu
  • 12,918
  • 8
  • 85
  • 98
3

The solution would be to have a regular view in the stack view to hold whatever views you are wanting to add constraints to, and then you can add constraints for your items that are relative to the views in the stack view. That way, your original views can have leading and trailing constraints within the stack view.

This can be done in the interface builder and programatically.

1

This question already has good answers, One suggestion though, use spacing property to set the spacing between the views. For first and last views there can be two options, either set insets as @tolpp suggested or add constraint attaching to parent (stackview) with constant to add padding.

infiniteLoop
  • 1,779
  • 22
  • 28
0

What we did was add transparent components (e.g., UIButton/UIView) as the first and last children of the UIStackView. Then set constrain the width of these invisible children to adjust the padding.

Crashalot
  • 31,452
  • 56
  • 235
  • 393
0

Set your stackview alignment to "center". After that you can give every subview different leading and trailing.

-2

Just add an empty view at the beginning of the stack view (also constraining its width and/or height):

stackView.insertArrangedSubview(UIView().constrain(width: 0, height: 0), at: 0)

and/or at the end:

stackView.addArrangedSubview(UIView().constrain(width: 0, height: 0))

I created this simple UIView extension to add the constraints:

extension UIView {
    func constrain(width: CGFloat, height: CGFloat) -> Self {
        NSLayoutConstraint.activate([
            widthAnchor.constraint(equalToConstant: width),
            heightAnchor.constraint(equalToConstant: height)
        ])

        return self
    }
}
Sergiu Todirascu
  • 1,235
  • 14
  • 18
-3

It seems that the solution was pretty simple. Instead of:

stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor).active = true

I just wrote:

stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor, constant: 15).active = true
Adrian
  • 16,820
  • 32
  • 99
  • 188
  • 1
    actually your code adds a leading for the uistackview inside the urscrollview, it doesn't add a padding for your views inside your uistackview, (as the question states) – William Kinaan Sep 14 '15 at 15:02
  • yeah, but I don't know if you can add padding, so this will work for me. – Adrian Sep 14 '15 at 17:17
  • as a first thought, you can another uistackview insiide your original uistackview and give the padding to it. then add your views to this new uistackview (you can do that completely by interface builder, no need to write code for it) – William Kinaan Sep 14 '15 at 19:17
  • Yes, that will work. You can added as an answer and I will accept it. – Adrian Sep 15 '15 at 06:44