Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add leading padding to view added inside an UIStackView

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


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


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.


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)...

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.


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)


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