gpt4 book ai didi

Swift:添加 NSLayoutConstraint 问题

转载 作者:行者123 更新时间:2023-11-28 07:03:30 25 4
gpt4 key购买 nike

我试图在 tableView 和 View Controller 的 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])

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

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

关于Swift:添加 NSLayoutConstraint 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com