"View hierarchy not prepared for constraint" Swift error 3
I am trying to add a button and set constraints programmatically, but I keep getting this error and cannot figure out what is wrong with my code. I have looked at other questions here, but they were not very helpful in my case.
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.backgroundColor = UIColor.lightGray
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0)
let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
btn.addConstraints([left, right, top])
source to share
When adding constraints to a view, "any species participating [in the constraint] must be either the recipient itself or a subview of the admission." You add a constraint to btn
, so it doesn't know what to do with the view
constraint referenced, because it is not btn
, and also a subset btn
. The error will be resolved if you added restrictions on view
instead of btn
.
Or even better, as Khalid said, use instead activate
, in which case you don't have to worry about where in the view hierarchy you add the constraint:
let btn = UIButton(type: .system)
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(.blue, for: .normal)
btn.backgroundColor = .lightGray
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
btn.leftAnchor.constraint(equalTo: view.leftAnchor),
btn.rightAnchor.constraint(equalTo: view.rightAnchor),
btn.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
])
source to share
Use activation restriction. how to turn off iOS 9 you can activate
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.backgroundColor = UIColor.gray
btn.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(btn)
let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0)
let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0)
let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
// here you have to call activate constraints everything will work
NSLayoutConstraint.activate([left, right, top])
source to share