Swift:添加NSLayoutConstraint问题

Swift: Adding NSLayoutConstraint Issues

我正在尝试在 tableView 和视图控制器的 view 之间创建布局约束。基本上 tableView 直接在主视图内。

这里:

let leftConstant = CGFloat(250.0) 

let topConstraint = NSLayoutConstraint(item: menuTableView,
     attribute: .Top,
     relatedBy: .Equal,
        toItem: self.topLayoutGuide,
     attribute: .Bottom,
    multiplier: 1,
     constant: 0.0)

let leftConstraint = NSLayoutConstraint(item: menuTableView,
    attribute: .LeadingMargin,
    relatedBy: .Equal,
       toItem: view,
    attribute: .LeadingMargin,
   multiplier: 1,
     constant: -leftConstant)

let bottomConstraint = NSLayoutConstraint(item: menuTableView,
    attribute: .Bottom,
    relatedBy: .Equal,
       toItem: self.bottomLayoutGuide,
    attribute: .Top,
   multiplier: 1,
     constant: 0.0)

let widthConstraint = NSLayoutConstraint(item: menuTableView,
    attribute: .Width,
    relatedBy: .Equal,
       toItem: nil,
    attribute: .NotAnAttribute,
   multiplier: 0,
     constant: leftConstant)

let verticalCenterConstraint = NSLayoutConstraint(item: menuTableView,
    attribute: .CenterX,
    relatedBy: .Equal,
       toItem: view,
    attribute: .CenterX,
   multiplier: 1,
     constant: 0.0)

menuTableView.addConstraints([topConstraint, leftConstraint, bottomConstraint, widthConstraint, verticalCenterConstraint])

...我收到此错误:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:<NSLayoutConstraint:0x16d18490 V:[_UILayoutGuide:0x16d24de0]-(0)-[UITableView:0x172a3800]> view:<UITableView: 0x172a3800; frame = (0 0; 250 568); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x16e23190>; layer = <CALayer: 0x16e24e20>; contentOffset: {0, 0}; contentSize: {250, 74}>'

通过替换

menuTableView的约束添加到自身
menuTableView.addConstraints([topConstraint, leftConstraint, bottomConstraint, widthConstraint, verticalCenterConstraint])

menuTableView.addConstraint(widthConstraint)

并将这些约束添加到 view

view.addConstraints([topConstraint, leftConstraint, bottomConstraint])

因为持有约束的视图必须是约束涉及的视图的祖先

**并且您必须选择.Leading.CenterX,否则您将得到unable to simultaneously satisfy constraints