Search code examples
iosswiftconstraintsnslayoutconstraint

Unable to Activate Constraints


I am receiving the error..

Terminating app due to uncaught exception 'NSGenericException', reason: '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.'

I referenced other answers and the solution consistently had been to add the subview in viewDidLoad prior to activating constraints programmatically.

I am still receiving however the same crash and do not understand what is causing it. Any guidance would be appreciated. Below is relevant code:

@IBOutlet weak var activityIndicatorView: UIView!
@IBOutlet weak var refreshActivityIndicatorView: UIView!

let activityIndicator = AnimationView(name: "name")
let refreshActivityIndicator = AnimationView(name: "name")

override func viewDidLoad() {
    super.viewDidLoad()
    activityIndicatorView.addSubview(activityIndicator)
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    refreshActivityIndicatorView.addSubview(activityIndicator)
    refreshActivityIndicator.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        activityIndicator.centerXAnchor.constraint(equalTo: activityIndicatorView.centerXAnchor),
        activityIndicator.centerYAnchor.constraint(equalTo: activityIndicatorView.centerYAnchor),
        activityIndicator.widthAnchor.constraint(equalToConstant: activityIndicatorView.frame.width),
        activityIndicator.heightAnchor.constraint(equalToConstant: activityIndicatorView.frame.height),
        refreshActivityIndicator.centerXAnchor.constraint(equalTo: refreshActivityIndicatorView.centerXAnchor),
        refreshActivityIndicator.centerYAnchor.constraint(equalTo: refreshActivityIndicatorView.centerYAnchor),

    refreshActivityIndicator.widthAnchor.constraint(equalToConstant: refreshActivityIndicatorView.frame.width),

    refreshActivityIndicator.heightAnchor.constraint(equalToConstant: refreshActivityIndicatorView.frame.height)
    ])
}

Solution

  • Replace

    refreshActivityIndicatorView.addSubview(activityIndicator)
    

    with

    refreshActivityIndicatorView.addSubview(refreshActivityIndicator)
    

    as those why the crash

    refreshActivityIndicator.centerXAnchor.constraint(equalTo: refreshActivityIndicatorView.centerXAnchor),
    refreshActivityIndicator.centerYAnchor.constraint(equalTo: refreshActivityIndicatorView.centerYAnchor), 
    refreshActivityIndicator.widthAnchor.constraint(equalToConstant: refreshActivityIndicatorView.frame.width), 
    refreshActivityIndicator.heightAnchor.constraint(equalToConstant: refreshActivityIndicatorView.frame.height)
    

    You set constraints between refreshActivityIndicatorView and refreshActivityIndicator while refreshActivityIndicator isn't added as a subview