I have a UISearchController whose search bar I am attempting to add to my view controller's view programmatically using autolayout constraints. I believe I have added the constraints properly, however when the view loads and I click the search bar, my app crashes with the message:
The view hierarchy is not prepared for the constraint...When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
Many others have had a similar problem, but their issue normally is that they are adding constraints to the wrong view. As far as I can tell, I have added my constraints correctly. Any ideas why I am getting this error? The relevant code, from viewDidLoad:
self.searchController.searchBar.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(self.searchController.searchBar)
let heightConstraint = NSLayoutConstraint(item: self.searchController.searchBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44)
self.searchController.searchBar.addConstraint(heightConstraint)
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height
let navigationBarHeight = self.navigationController?.navigationBar.frame.size.height
let searchBarTopConstraint = NSLayoutConstraint(item: self.searchController.searchBar, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: (statusBarHeight + navigationBarHeight!))
let searchBarLeftConstraint = NSLayoutConstraint(item: self.searchController.searchBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let searchBarRightConstraint = NSLayoutConstraint(item: self.searchController.searchBar, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)
self.view.addConstraints([searchBarTopConstraint, searchBarLeftConstraint, searchBarRightConstraint])
The constraint that is giving me the error is searchBarTopConstraint.