Search code examples
iosxcodeuiviewinterface-buildersafearealayoutguide

Adding margins to a scene that uses the Safe Area


Is it possible to constrain to the Safe Area AND use margins?

I'm following Build a Basic UI here. In the "Adopt Auto Layout" section, I'm supposed to add constraints to my stack view:

Adding Constraints

Even though I have "Constrain to margins" checked, here is what results:

enter image description here

No margins! The Stack View is now constrained to the Safe Area, which I don't think existed when that tutorial was written. Apparently the Safe Area doesn't allow you to constrain "Relative to margin" (that option is missing from the constraint dropdown):

enter image description here

I know I can turn Safe Area off (View > Utilities > Show File Inspector and deselect the checkbox for Use Safe Area Layout Guides) as this thread recommends as the solution, resulting in the following:

Margins enabled

But I'd rather not lose the functionality of the Safe Area.

Is it not possible to use the Safe Area while taking advantage of layout margins? What is the recommended way to add margins into a scene that uses the Safe Area? There must be an elegant solution achievable through Interface Builder.


Solution

  • You can make use of the default view margins by embedding your UIStackView inside a UIView:

    enter image description here