无法激活,因为它们没有共同的祖先 IBOutlet 和代码

Unable to activate because they have no common ancestor IBOutlet and code

我正在尝试向我创建并以编程方式添加到视图的表视图添加约束。我想基于 UITextField 来约束它,它是 IBOutlet。但是,我收到以下错误:

*** 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.'

@IBOutlet weak var authorTextField: UITextField!

override func viewDidLoad() {
    myTableView = MyTableView(frame: CGRect(x: 0, y: 80, width: 320, height: 120), style: .plain)
    myTableView!.isHidden = false
    myTableView!.backgroundColor = UIColor.green
    self.view.addSubview(myTableView!)
    myTableView.setConstraints(to: authorTextField)  // <-- this fails

// MyTableView.swift ..
func setConstraints(to view: UIView)
    self.translatesAutoresizingMaskIntoConstraints = false
    self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0).isActive = true
    self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8.0).isActive = true
}

如何添加这个约束?

答案在错误消息中。您的 属性 authorTextField 在另一个视图层次结构中。进入故事板并将文本字段放在同一视图中。另一方面,不要混合设置框架和自动布局约束,我认为您在这里感到困惑。而不是

MyTableView(frame: CGRect(x: 0, y: 80, width: 320, height: 120), style: .plain)

MyTableView(frame: CGRect.zero, style: .plain)

并为您的 setConstraints 添加高度限制 方法

self.view.heightAnchor.constraint(equalToConstant: 120).isActive = true

您应该使用它而不是您的代码: 对于设置约束,您应该将代码修改为以下内容:

func setConstraints(to view: UIView , superView: UIView) {
    self.translatesAutoresizingMaskIntoConstraints = false
    let leading = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0.8)
    let trailing = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -0.8)
    let width = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 320)
    let height = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 120)
    superView.addConstraints([leading, trailing])
    self.addConstraints([width, height])
}

第一部分:最好将 MyTableView 对象定义为零帧(它只是帮助您不要弄错)并将视图控制器发送到约束,因为它需要向层次结构位置添加约束。 所以请喜欢以下内容:

myTableView = MyTableView(frame: .zero, style: .plain)
myTableView!.isHidden = false
myTableView!.backgroundColor = UIColor.green
self.view.addSubview(myTableView!)
myTableView.setConstraints(to: authorTextField , superView: self)

如果您没有将视图添加到视图层次结构中,就会遇到这个问题。我添加了 addSubview 并且运行良好

addSubview(view)

self.view.addSubview(view)