以下是我的以下代码:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.white
let headerLabel = UILabel(frame: CGRect(x: 30, y: 0, width:
tableView.bounds.size.width, height: tableView.bounds.size.height))
headerLabel.font = UIFont().robotoMedium(withFontSize: 10)
headerLabel.textColor = CustomColor.lightGrey.color
headerLabel.text = "Travel Shops"
headerLabel.sizeToFit()
headerView.addSubview(headerLabel)
headerLabel.translatesAutoresizingMaskIntoConstraints = false
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: tableView, attribute: .trailing, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: tableView, attribute: .leading, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 131))
return headerView
}
但是应用程序崩溃了以下内容:
添加到视图时,约束的项必须是该视图的后代(或视图本身)。如果在组装视图层次结构之前需要解析约束,则会崩溃。打破 - [UIView(UIConstraintBasedLayout)_viewHierarchyUnpreparedForConstraint:]进行调试。
答案 0 :(得分:6)
headerLabel
是headerView
的子视图,headerView
是层次结构中TableView
的子项,这就是显示此消息的原因,您需要将约束添加到{{1}这是headerView
而不是UITableView,headerLabel.superView
更改您的代码
headerLabel.superView.superView
由此
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: headerView, attribute: .trailing, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
headerLabel.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 131))
希望这有帮助