无法激活约束

时间:2019-03-20 23:39:53

标签: ios swift constraints nslayoutconstraint

我收到错误消息。

  

由于未捕获的异常“ NSGenericException”而终止应用程序,   原因:“无法激活锚点约束,因为   他们没有共同的祖先。约束或其锚点吗   不同视图层次结构中的参考项目?那是非法的。'

我引用了其他答案,解决方案始终是在以编程方式激活约束之前在viewDidLoad中添加子视图。

但是我仍然收到相同的崩溃,并且不知道是什么原因造成的。任何指导将不胜感激。下面是相关代码:

@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)
    ])
}

1 个答案:

答案 0 :(得分:0)

替换

refreshActivityIndicatorView.addSubview(activityIndicator)

使用

refreshActivityIndicatorView.addSubview(refreshActivityIndicator)

那些崩溃的原因

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)

您在refreshActivityIndicatorViewrefreshActivityIndicator之间设置了约束,而没有将refreshActivityIndicator添加为子视图