Unable to activate constraint with anchors because they have no common ancestor

Marcus Levi picture Marcus Levi · Mar 31, 2018 · Viewed 7.1k times · Source

I have added a view called myView in interface builder as can be seen in the code below and have added this to the main view as a subview, I have then added three buttons programatically. I have added these as subviews to the main view before trying to apply anchor constraints. I have also set the buttons to translatesAutoresizingMaskIntoConstraints = false. Does anyone one know what i am doing wrong here to be getting the following error?

Unable to activate constraint with anchors because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Warmup button
        view.addSubview(myView)
        myButton = dropDownButton.init(frame: CGRect(x: 0,y: 0, width: 0, height: 0))
        self.view.addSubview(myButton)
        myButton.translatesAutoresizingMaskIntoConstraints = false
        myButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        myButton.centerYAnchor.constraint(equalTo: self.myView.topAnchor, constant: 38).isActive = true
        myButton.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
        myButton.heightAnchor.constraint(equalToConstant: 76).isActive = true
        myButton.dropView.dropDownOptions = ["Chest Expansions", "Side Arm Raises", "Dives", "Raised Arm Circles", "Overhead Punches", "Punches"]

        //stretches button
        myStretchesButton = dropDownButton.init(frame: CGRect(x: 0,y: 0, width: 0, height: 0))
        myStretchesButton.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myStretchesButton)
        myStretchesButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        myStretchesButton.centerYAnchor.constraint(equalTo: self.myButton.dropView.bottomAnchor, constant: 38).isActive = true
        myStretchesButton.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
        myStretchesButton.heightAnchor.constraint(equalToConstant: 76).isActive = true
        myStretchesButton.dropView.dropDownOptions = ["Chest Expansions", "Side Arm Raises", "Dives", "Raised Arm Circles", "Overhead Punches", "Punches"]

    }

Answer