0
votes

because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies?

override func viewDidLoad() {
        super.viewDidLoad()

        let myContainer = UIView()
        myContainer.backgroundColor = .purple
        myContainer.translatesAutoresizingMaskIntoConstraints = false
        myContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        myContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myContainer.widthAnchor.constraint(equalToConstant: 200).isActive = true
        myContainer.heightAnchor.constraint(equalToConstant: 200).isActive = true
        self.view.addSubview(myContainer)
}

ERROR:

2019-11-06 20:06:17.763701-0600 Testing AutoLayout[42202:4013241] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

If I comment the following two lines the error goes away and myContainer view shows in the upper-left corner.

    //myContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    //myContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

Any idea why the error if 'myContainer' is the only thing I have?

2
On a side note. Here is a better way to activate constraints hackingwithswift.com/example-code/uikit/….Rakesha Shastri

2 Answers

3
votes

You should add the view before constraints

let myContainer = UIView()
self.view.addSubview(myContainer)
myContainer.backgroundColor = .purple
myContainer.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    myContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    myContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    myContainer.widthAnchor.constraint(equalToConstant: 200),
    myContainer.heightAnchor.constraint(equalToConstant: 200)
])

The reason why width and height constraints pass , is that both of them are added to the view itself while centerX and centerY are added to the parent view.

2
votes

First of all you should add views (one or more views) before adding constraints.

override func viewDidLoad() {
      super.viewDidLoad()
let myContainer = UIView()
self.view.addSubview(myContainer)
myContainer.backgroundColor = .ColorName
myContainer.translatesAutoresizingMaskIntoConstraints = false
addViewConstraints()
}

func addViewConstraints () {
NSLayoutConstraint.activate([
    myContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    myContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    myContainer.widthAnchor.constraint(equalToConstant: 200),
    myContainer.heightAnchor.constraint(equalToConstant: 200)
])
}