有自定义静态标头TableViews两个主要选项:
willDisplayHeaderView提供了默认的视图,并允许它修改。简单的外观修改相当简单。添加按钮等交互功能有点复杂
viewForHeaderInSection返回标题的视图,该标题可以从nib加载或完全由代码创建。这样做的一个缺点是它不能访问标题的默认外观,并且Apple仅提供对一个默认(UIColor.groupTableViewBackground)的访问。
要在默认标题之上构建,需要使用willDisplayHeaderView。
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header = view as! UITableViewHeaderFooterView
let headerLabelFont: UIFont = header.textLabel!.font
// References for existing or new button
var selectButton: UIButton? = nil
// Check for existing button
for i in 0..<view.subviews.count {
if view.subviews[i] is UIButton {
selectButton = view.subviews[i] as? UIButton
}
}
// No button exist, create new one
if selectButton == nil {
selectButton = UIButton(type: .system)
header.addSubview(selectButton!)
toggleButton = UIButton(type: .system)
header.addSubview(toggleButton!)
}
// Configure button
selectButton?.frame = CGRect(x: view.frame.size.width - 85, y: view.frame.size.height - 28, width: 77, height: 26)
selectButton?.tag = section
selectButton?.setTitle("SELECT ALL", for: .normal)
selectButton?.titleLabel?.font = UIFont(descriptor: headerLabelFont.fontDescriptor, size: 11)
selectButton?.contentHorizontalAlignment = .right;
selectButton?.setTitleColor(self.view.tintColor, for: .normal)
selectButton?.addTarget(self, action: #selector(self.selectAllInSection), for: .touchUpInside)
}
func selectAllInSection() {
...
的最大挑战是努力回避的事实,静态头细胞可以通过TableView中重复使用。因此,如果修改了一个,例如添加一个按钮,那么当它被重用时,可以添加第二个按钮。这只是一个问题,如果TableView的大小足以滚动屏幕,但应该防范,因为结果可能很难追查。
如果将多个按钮添加到标题,则需要一些标识每个按钮的机制。 UIButton.tag是一个选项,但在此示例中,该字段用于标识要执行的部分。另一种选择是使用标签字符串来包含两条信息。
一个完整的工作演示可以Github
找到(是回答我的问题,希望为浸出年后回来给的东西)