您正在寻找的是节标题。您可以通过实现UITableViewDataSource 方法轻松配置自己的自定义视图
例如:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
// configure view, note the method gives you the section to help this process
return headerView
}
你可能还想实现这个功能
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50 // or whatever it is
}
请记住,默认情况下标题是粘性的
过去,我很容易解决这个问题:
let dummyViewHeight = CGFloat(49) // height of header (set in storyboard)
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
self.tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)
这基本上只是让表格标题“粘”在表格顶部的这个插图上。 (除非您真的希望它悬停在顶部的部分上)
编辑:
鉴于 OP 认为这“不令人满意”,当我说唯一的其他合理选择(如果您不想使用部分页眉或页脚视图)时,我有 99% 的信心然后制作一个新的UITableViewCell 子类。然后新的子类将出现在每个部分的顶部。
因此,在cellForIndexPath: 方法中,您将检查是否indexPath.row == 0,如果是,则将具有不同标识符的单元格出列。这样,标题就变成了一个构建方式不同的单元格。
如果您以编程方式执行此操作,请务必注册该单元格 (tableView.register(MyNewHeaderCellSubclass.self, forCellReuseIdentifier: "MyNewHeaderCellSubclass")),或者转到情节提要上的表格视图并切换两种类型的动态单元格类的选项。
但是,节标题正是这个用例的用途。如果不完全放弃UITableView,我想不出任何其他解决方案,我认为这将是一个大错误。如果是这样的话,祝你好运。