Search code examples
iosxcodeautolayoutmarginsstackview

Stack View constrained to margins leaves no margin


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)


Solution

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