简体   繁体   中英

How to add a subview with constraints to make the subview with the same frame as its superview?

Within UIView I have a method presentView() :

public func presentView() {

    UIApplication.sharedApplication().delegate?.window??.addSubview(self)

    let blurEffect = UIBlurEffect(style: .Light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.backgroundColor = UIColor.yellowColor()
    addSubview(blurEffectView)

    let topConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
    let leadingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
    let trailingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

    self.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])

    print("newframe: \(blurEffectView.frame)")

}

but sth is wrong because this is the output on console:

newframe: (0.0, 0.0, 0.0, 0.0)

and result is:

在此处输入图片说明

Remember about:

blurEffectView.translatesAutoresizingMaskIntoConstraints = false

and then:

let topConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0)

addSubview(blurEffectView)
addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
layoutIfNeeded()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM