无法激活约束
Posted
技术标签:
【中文标题】无法激活约束【英文标题】:Unable to Activate Constraints 【发布时间】:2019-03-20 23:39:53 【问题描述】:我收到了错误..
由于未捕获的异常“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】:替换
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)
您在refreshActivityIndicatorView
和refreshActivityIndicator
之间设置了约束,而refreshActivityIndicator
没有作为子视图添加
【讨论】:
以上是关于无法激活约束的主要内容,如果未能解决你的问题,请参考以下文章
使用约束在 UITableViewController 中添加 UIActivityIndicatorView 时出错。无法使用 SnapKit 使用锚激活约束