问题以编程方式设置约束Swift

时间:2018-09-24 12:05:39

标签: ios swift uitableview autolayout constraints

我想将UISegmentedControl放在使用所有水平空间的UITableView的标头中。

这是这样的:

enter image description here

我想使用所有空间,所以我想设置约束。我尝试过:

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.'

1 个答案:

答案 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])