Layout Margin Guide for AutoLayout in iOS

Jul 27, 23

UIKit provides us the way to provide default margins to our views using the layoutMarginGuide. Instead of using view.trailing we can use view.layoutMarginGuide.trailing which will give a default trailing margin of 16 or 20 points depdending on the width of the screen. This helps us have consistent margins throughout our app. And instead when we want to change these margins we can simply change them by setting directionalLayoutMargins. Following example increases the trailing margin to 140 points for that view

view.directionalLayoutMargins.trailing = 140

This will allow you to increase the value but you cannot set it to below a minimum value. To set it something much smaller then the recomended points we need to shut of the minimum layout margins.

viewRespectsSystemMinimumLayoutMargins = false
view.directionalLayoutMargins.trailing = 140