我想将UISegmentedControl
放在使用所有水平空间的UITableView
的标头中。
这是这样的:
我想使用所有空间,所以我想设置约束。我尝试过:
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.'
答案 0 :(得分:2)
您需要在激活约束之前将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])