我尝试在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}>'
答案 0 :(得分:1)
通过替换
将menuTableView
的约束添加到自身
menuTableView.addConstraints([topConstraint, leftConstraint, bottomConstraint, widthConstraint, verticalCenterConstraint])
带
menuTableView.addConstraint(widthConstraint)
并将这些约束添加到view
view.addConstraints([topConstraint, leftConstraint, bottomConstraint])
因为持有约束的视图必须是约束涉及的视图的祖先
**,您必须选择.Leading
或.CenterX
,否则您将获得unable to simultaneously satisfy constraints
。