2
votes

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:

enter image description here

1
If I'm reading correctly, self is a UIView. Then you should add the constraints to self rather then blurEffectView.Dániel Nagy
@DánielNagy I updated the question, can you help me to solve this out?Bartłomiej Semańczyk
I think until the view is not layed out, you won't get it's actual frame. So after self.addConstraints you won't get it right now.Dániel Nagy
Again updated the question with new info. I set background color to yellow, but there is no my view at all.Bartłomiej Semańczyk
This SO question has a lot of good information on programmatically adding constraints.Derek Soike

1 Answers

13
votes

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()