周围可以有2个案例,
-
如果您只想为每个 section 添加 String 标题,请实现 UITableViewDataSource's tableView(_: titleForHeaderInSection:) 方法。
-
如果您想为每个section 提供一个自定义view,请实现UITableViewDelegate's tableView(_:viewForHeaderInSection:) 方法。
这是tableView(_: titleForHeaderInSection:) 的示例,
class VC: UIViewController, UITableViewDataSource {
let data = [["1","2","3"], ["4","5"]]
let sectionNames = ["This is Sec-1", "And this is Sec-2"]
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.textLabel?.text = data[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionNames[section]
}
}
如果您需要为每个section 自定义高度,请实现tableView(_:heightForHeaderInSection:)。
截图:
编辑:
使用accessoryType 作为.checkmark 进行单元格选择。
像这样创建一个自定义的UITableViewCell 和override setSelected(_:animated:) 方法,
class CustomCell: UITableViewCell {
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
}
}
将xib中的CustomCell的reuseIdentifier设置为cell。此外,更新tableView(_:cellForRowAt:) 方法以使CustomCell 实例出列。我在上面的代码中更新了它。