如何添加uitableviewcell类型的自定义单元格作为tableview表头



我有一个自定义的表视图单元格,用于许多不同的表视图。现在,我的要求是在其中一个表视图中使用相同的表视图单元格作为标题。但我面临的问题是,我不想更改自定义表单元格中的任何内容,但在构建表视图的单元格时,我想在其中添加头视图。目前,我正在做的事情是这样的:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let model = model as? AParticularModel {
if let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellHeader", for: indexPath) as? CustomCellHeader {
cell.configure(tit: model.title)
cell.delegate = self
tableView.tableHeaderView = cell.contentView
}
if let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell") as? TableCell {
cell.configureCell(with: model.data[indexPath.row])
return cell
}
}

目前的问题是:

  1. TableHeader占用了大量空间,我不确定如何分配高度
  2. TableHeader有一个无法单击的按钮

您应该为部分使用UITableViewDelagates和Datasource函数。

试试这个:

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let headerView = tableView.dequeueReusableCell(withIdentifier: "CustomCellHeader") as? CustomCellHeader {
cell.configure(tit: model.title)
cell.delegate = self
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return anyArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell") as? TableCell {
cell.configureCell(with: model.data[indexPath.row])
return cell
}
}

您可以根据自己的选择添加节数,也可以分别设置页眉的单元格和其他单元格的高度。

如您所知,为表视图提供一个headerview通常用于修复视图到特定部分。如果你在单元格中使用它,当你向下滚动表视图时,你的标题不会出现,直到你滚动到顶部。如果你想做这种行为,最好使用节而不是头视图。

无论如何,您可以使用以下代码从customcell 进行头视图

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellHeader") as? CustomCellHeader {
cell.configure(tit: model.title)
cell.delegate = self
return cell
}

和高度

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return yourDesireHeight
}

最新更新