Setting Layoutmargins of Uiview Doesn't Work

Setting layoutMargins of UIView doesn't work

Custom layoutMargins don't work on a view that is the root to a UIViewController instance. Those are defined by the system and cannot be overridden.
You need to add another subview that will hold all of your content, you can then modify the layout margins on this new "contentView"

Update:

Discussion

Use this property to specify the desired amount of space (measured in points) between the edge of the view and any subviews.
Auto layout uses your margins as a cue for placing content. For
example, if you specify a set of horizontal constraints using the
format string “|-[subview]-|”, the left and right edges of the subview
are inset from the edge of the superview by the corresponding layout
margins. When the edge of your view is close to the edge of the
superview and the preservesSuperviewLayoutMargins property is YES, the
actual layout margins may be increased to prevent content from
overlapping the superview’s margins.

The default margins are eight points on each side.

If the view is a view controller’s root view, the system sets and
manages the margins. The top and bottom margins are set to zero
points. The side margins vary depending on the current size class, but
can be either 16 or 20 points. You cannot change these margins.

How to change the layout margins programmatically

This seems to be fixed/changed for iOS 11. Lower versions are out of luck.

I've elaborated more in this question

Add layoutMargins to one element in a UIStackView

Here is an extension I made that helps to achieve fast such margins :

extension UIStackView {

func addArrangedSubview(_ v:UIView, withMargin m:UIEdgeInsets )
{
let containerForMargin = UIView()
containerForMargin.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
v.topAnchor.constraint(equalTo: containerForMargin.topAnchor, constant:m.top ),
v.bottomAnchor.constraint(equalTo: containerForMargin.bottomAnchor, constant: m.bottom ),
v.leftAnchor.constraint(equalTo: containerForMargin.leftAnchor, constant: m.left),
v.rightAnchor.constraint(equalTo: containerForMargin.rightAnchor, constant: m.right)
])

addArrangedSubview(containerForMargin)
}
}

Auto Layout: layoutMarginsGuide

It seems to me that layoutMarginsGuide is not ready in the init method of a UIView. I'm also getting similar issues, where setting up the constraints in updateConstraints just works. Still investigating why.

UPDATE: What I was trying to do was set the layoutMargins before the view had been added to a superview (in the init). That didn't work. What did work was setting the constraints in the init, relative to layoutMarginsGuide, but actually setting the layoutMargins in viewDidMoveToSuperView.



Related Topics



Leave a reply



Submit