我有一个分组的表格视图,出于某种原因,所有部分标题仅显示在一个部分中。所以结果是标题在 section = 0 中都在彼此之上。所有其他部分都是空白的。
我尝试调试,发现当 section == 1 时,headerLabel 为 nil。
我使用自定义视图作为标题,代码如下:
class HeaderView: UIView {
let headerLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
addCustomView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView() {
self.addSubview(headerLabel)
NSLayoutConstraint.activate(headerLabelConstraints())
}
private func headerLabelConstraints() -> [NSLayoutConstraint] {
let leadingAnchor = headerLabel.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor)
let trailingAnchor = headerLabel.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor)
let topAnchor = headerLabel.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor)
let heightAnchor = headerLabel.heightAnchor.constraint(equalToConstant: 44)
headerLabel.translatesAutoresizingMaskIntoConstraints = false
return [leadingAnchor, trailingAnchor, topAnchor, heightAnchor]
}
}
这是我在 tableView 中的调用方式:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! HeaderView
}
//for reference: sectionHeaderHeight = 44
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.sectionHeaderHeight
}
//for reference: sectionTitles = ["title1", "title2", "title3"]
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = HeaderView(frame: CGRect.zero)
headerView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
headerView.headerLabel.text = sectionTitles[section]
headerView.headerLabel.textColor = UIColor.black
return headerView
}
谢谢!