When i was trying to create layout constraints, i read about NSLayoutAnchor class. They said:
Note
UIView does not provide anchor properties for the layout margin attributes. Instead, the layoutMarginsGuide property provides a UILayoutGuide object that represents these margins. Use the guide’s anchor properties to create your constraints
Ok. But simultaneously I crated anchor properties for the layout margin properties without UILayoutGuide property.
let inputsContainerView = UIView()
inputsContainerView.backgroundColor = UIColor.white
inputsContainerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(inputsContainerView)
//need x,y,width,height constraints
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
inputsContainerView.heightAnchor.constraint(equalToConstant: 150).isActive = true
So then why do we need UILayoutGuide object? And it turns out UIView does provide anchor properties for the layout margin attributes? Please if someone know anything I would very appreciated.
It depends on your design requirements.
layoutMarginsGuide
documentation states:Where Layout Margins is basically just the safe area of a view:
For
self.view
, the visible portion of the overall interface would exclude the areas taken up by status bar, navigation bar, tab bar, etc.For a normal
UIView
, the default padding is 8px.So basically, if you want
someView
to be constrained within the safe area / margin ofotherView
, then you will referenceotherView
'slayoutMarginsGuide
anchors.If not, then just
otherView
's anchors are enough.1. Example (with
layoutMarginsGuide
):Output:
Observation:
self.view
's left/right edgesself.view
's safe area / layout margins2. Example (without
layoutMarginsGuide
):Output:
Observation:
self.view
's left/right edgesself.view
's top edge which overlaps the status barself.view
's boundsFinally, it depends on your requirement.
Sometimes you should use it, sometimes you could use it, sometimes you just don't need to use it.
PS: Now, whether you base it on the
UIView
's anchors or it'slayoutMarginsGuide
anchors, it will respond to device rotation or any other layout changes automatically.