我正在使用viewForHeaderInSection
实现标头单元。
我创建了一个单独的视图,高度为1,我假设它应显示为分隔符。
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! CustomHeaderCell
cell.opt.text = "Some"
cell.len.text = "LEN"
cell.wgt.text = "WGT"
if !cell.constraintsInstalled {
let constraints = [
cell.stackView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
cell.stackView.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor),
cell.stackView.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
cell.stackView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor)
]
cell.contentView.addConstraints(constraints) //vw.addSubview(headerCell)
let separatorView = UIView(frame: CGRect(x: tableView.separatorInset.left, y: cell.frame.height, width: tableView.frame.width - tableView.separatorInset.right, height: 1))
separatorView.backgroundColor = UIColor.red
cell.addSubview(separatorView)
}
return cell
}
答案 0 :(得分:1)
首先,您应该将其添加到contentView
cell.contentView.addSubview(separatorView)
第二个不要使用框架,因为尚未放置单元格,还应该使用约束
separatorView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
separatorView.leadingAnchor.constraint(equalTo:cell.contentView.leadingAnchor),
separatorView.trailingAnchor.constraint(equalTo:cell.contentView.trailingAnchor),
separatorView.heightAnchor.constraint(equalToConstant:1),
separatorView.bottomAnchor.constraint(equalTo:cell.contentView.bottomAnchor)
])