7

I got some problem that I'm not sure how to solve... I'm working on some lessons which are a little bit old (they are done in Swift 3), and I got a problem with constraints and margins. I'm just following the lesson and it says that for that stack view I need to put following constraints: Given constraints

After adding constraints to stack view I got this result:

Result

and this is the result I expected:

Expected Result

So my question is Why that stack view goes over margins, and how to fix it. (reminder lesson was in Swift 3 and they got stack view inside the margins)

vacawama
  • 150,663
  • 30
  • 266
  • 294

1 Answers1

7

Yes. That is confusing. Selecting Constrain to margins used to leave a gap on the sides. Now, when you select Constrain to margins, it constrains your view to the Safe Area but the view extends to the sides when the constant is 0.

To fix it, change your leading and trailing constraints:

  1. Open your leading constraint. Click on Safe Area.leading and in the pop up select Superview.
  2. Now click on Superview.leading and select Relative to margin and set Constant back to 0.

Repeat this for the trailing constraint.


Alternate solution

Alternatively, you can leave your view constrained to the Safe Area and just set the constants to 16 (or -16 depending on the order of the items in the constraint).

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Weird! 1. Isn't this a bug? Or it's somehow by design? 2. It the same when you do through code? or it's only like this on storyboards? – mfaani Aug 01 '18 at 14:34
  • 1
    @Honey, **Constrain to margins** should be changed to **Constrain to safe area** if they're going to change what it does, IMHO. – vacawama Aug 01 '18 at 14:43
  • Thanks. didn't understand your answer to my 2nd question. If in code I constraint to margins with a constant of `0` would it be constrained to the margins or it would be constrained to the view's anchors itself ie it would work like the storyboard? – mfaani Aug 01 '18 at 14:56
  • @Honey, give me an example of how you would constrain to margins with a constant of 0 in code. – vacawama Aug 01 '18 at 15:01
  • func pinToAllMargins(of view: UIView){ let top = topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor) let leading = leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor) let trailing = trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor) let bottom = bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor) NSLayoutConstraint.activate([top, leading, trailing, bottom]) } – mfaani Aug 01 '18 at 15:07
  • 1
    @Honey, that works in code. I think the issue is merely how Interface Builder is interpreting *Constrain to margins*. It really treats it as *Constrain to safe area* and the fix listed in the answer restores it to how it used to behave. – vacawama Aug 01 '18 at 15:19