meowmeowmeow meowmeowmeow - 1 month ago 4
iOS Question

programmatic constraints - cover entire superview using layout anchors

Is it possible using layout anchors to cover an entire superview's screen?

Using NSLayoutConstraints, I can achieve this effect using the code below

dimmingView = UIView()
dimmingView.translatesAutoresizingMaskIntoConstraints = false
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)

containerView?.addSubview(dimmingView)

NSLayoutConstraint(item: containerView!, attribute: .leadingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .leadingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .trailingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .trailingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .topMargin, relatedBy: .equal, toItem: dimmingView, attribute: .topMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .bottomMargin, relatedBy: .equal, toItem: dimmingView, attribute: .bottomMargin, multiplier: 1, constant: 0).isActive = true


I want to switch to layout anchors instead, following what's suggested in the docs. I tried doing this:

let margins = containerView?.layoutMarginsGuide

dimmingView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
dimmingView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
dimmingView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
dimmingView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true


or this

let margins = containerView?.layoutMarginsGuide

dimmingView.heightAnchor.constraint(equalTo: margins.heightAnchor).isActive = true
dimmingView.widthAnchor.constraint(equalTo: margins.widthAnchor).isActive = true
dimmingView.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
dimmingView.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true


but both did not work. Instead of fully covering containerview, what I end up with are paddings at all 4 sides.

enter image description here

Answer

You are constraining to margins and the margins are the space you see. constrain to superview instead:.

    dimmingView.heightAnchor.constraint(equalTo: dimmingView.superview!.heightAnchor).isActive = true
    dimmingView.widthAnchor.constraint(equalTo: dimmingView.superview!.widthAnchor).isActive = true
    dimmingView.centerXAnchor.constraint(equalTo: dimmingView.superview!.centerXAnchor).isActive = true
    dimmingView.centerYAnchor.constraint(equalTo: dimmingView.superview!.centerYAnchor).isActive = true
Comments