以编程方式设置约束的问题 Swift
Posted
技术标签:
【中文标题】以编程方式设置约束的问题 Swift【英文标题】:Problem to set constraints programatically Swift 【发布时间】:2018-09-24 12:05:38 【问题描述】:我想在UITableView
的标题中放置一个UISegmentedControl
,以使用所有水平空间。
是这样的:
我想使用所有空间,所以我想设置约束。我试过这个:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
if section == 0
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height:
UITableViewAutomaticDimension))
headerView.backgroundColor = UIColor.white
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
var constraint = NSLayoutConstraint(item: segmentedControl, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 0)
var constraint2 = NSLayoutConstraint(item: segmentedControl, attribute: .trailing, relatedBy: .equal, toItem: headerView, attribute: .trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([constraint,constraint2])
headerView.addSubview(segmentedControl)
return headerView
但出现以下错误:
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x600000a7cbc0 "UISegmentedControl:0x7fc4cf480b20.leading"> and <NSLayoutXAxisAnchor:0x600000a7c7c0 "UIView:0x7fc4cf5b3f70.leading"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
【问题讨论】:
您在将 segmentedControl 添加到视图之前设置约束。您应该首先将其添加到视图中,然后设置它的约束 【参考方案1】:您需要在激活约束之前将segmentedControl
添加到headerView
var constraint = NSLayoutConstraint(item: segmentedControl, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 0)
var constraint2 = NSLayoutConstraint(item: segmentedControl, attribute: .trailing, relatedBy: .equal, toItem: headerView, attribute: .trailing, multiplier: 1, constant: 0)
headerView.addSubview(segmentedControl)
NSLayoutConstraint.activate([constraint,constraint2])
【讨论】:
这行得通。我会接受。但是当我把10
例如,拖尾保持在窗外。 imgur.com/PicTY0J。 let constraint2 = NSLayoutConstraint(item: segmentedControl, attribute: .trailing, relatedBy: .equal, toItem: headerView, attribute: .trailing, multiplier: 1, constant: 10)
max X of segment = max X of header + 10 ,所以如果你在视图中需要它,它应该是 -10 这就是约束最终被转换为 trailing = max X以上是关于以编程方式设置约束的问题 Swift的主要内容,如果未能解决你的问题,请参考以下文章
Swift iOS以编程方式在导航栏下方设置scrollView约束
如何在 Swift 中以编程方式在水平线上设置约束? [关闭]