我正在尝试寻找并思考这个问题,但我找不到解决它的最佳解决方案!我不明白这是什么意思?!
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.'
代码:
private let logoImageView: UIImageView = {
let imgView = UIImageView()
imgView.image = UIImage(named: "LogoBlue")
return imgView
}()
func setupLogo() {
if #available(iOS 11.0, *) {
view.add(subview: logoImageView) { (v, p) in [
v.topAnchor.constraint(equalTo: p.safeAreaLayoutGuide.topAnchor, constant: 50),
v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
]}
} else {
view.add(subview: logoImageView) { (v, p) in [
v.topAnchor.constraint(equalTo: p.topAnchor, constant: 50),
v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
]}
}
}
扩展名:
extension UIView {
func add(subview: UIView, createConstraints: (_ view: UIView, _ parebt: UIView) -> [NSLayoutConstraint]) {
subview.activate(constraints: createConstraints(subview, self))
}
func activate(constraints: [NSLayoutConstraint]) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints)
}
}
最佳答案
您需要添加UIView
在应用约束之前在层次结构上。
换句话说,您需要<#PARENT_HERE#>.addSubview(<#CHILD_HERE#>)
您可以将扩展名更改为:
extension UIView {
func add(subview: UIView, createConstraints: (_ view: UIView, _ parebt: UIView) -> [NSLayoutConstraint]) {
self.addSubview(subview) // <
subview.activate(constraints: createConstraints(subview, self))
}
func activate(constraints: [NSLayoutConstraint]) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints)
}
}
如果您可以修改您的扩展程序,这绝对是我的解决方案。
另一个不太花哨的解决方案是在扩展程序之外手动添加每个 subview :
func setupLogo() {
self.view.addSubview(logoImageView) // assuming self.view is not nil
if #available(iOS 11.0, *) {
view.add(subview: logoImageView) { (v, p) in [
v.topAnchor.constraint(equalTo: p.safeAreaLayoutGuide.topAnchor, constant: 50),
v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
]}
} else {
view.add(subview: logoImageView) { (v, p) in [
v.topAnchor.constraint(equalTo: p.topAnchor, constant: 50),
v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
]}
}
}
注意:这是辅助解决方案,请勿同时使用两者。
关于ios - 由于未捕获的异常 'NSGenericException' 而终止应用程序,原因 : 'Unable to activate constraint with anchors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565684/