Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View hierachy not prepared for constraint

override func viewDidLoad() {
    super.viewDidLoad()

    self.blurView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) as UIVisualEffectView
    self.view.insertSubview(self.blurView, belowSubview: self.filterPanel)

    self.blurView.addConstraint(NSLayoutConstraint(item: self.blurView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
    self.blurView.addConstraint(NSLayoutConstraint(item: self.blurView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
    self.blurView.addConstraint(NSLayoutConstraint(item: self.blurView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
    self.blurView.addConstraint(NSLayoutConstraint(item: self.blurView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
}

When the above code is called it crashes with the error "The view hierarchy is not prepared for the constraint". I can understand this error being generated if I'm trying to add the constraint before it's been added to the view but the view is inserted which is then followed by the constraints being added.

Any ideas?

like image 343
user3605739 Avatar asked Jan 09 '23 21:01

user3605739


1 Answers

Constraints need to be added to a common ancestor of all involved views (where a view is considered an ancestor of itself for this purpose). self.blurView is a subview of self.view. The constraints involve both self.blurView and self.view. Therefore, the constraints need to be added to self.view, not self.blurView.

By the way, your clue should be this part of the error message (which you didn't quote, but your associated did here):

When added to a view, the constraint's items must be descendants of that view (or the view itself).

like image 197
Ken Thomases Avatar answered Jan 15 '23 19:01

Ken Thomases