如何在 UITableView 部分之间添加分隔符?

How to add separators between UITableView sections?

我正在实现一个表视图,它有 3 个部分(部分计数保持不变)并且每个部分包含几行。

行为 1: 仅将部分 header 添加到第三部分。

我是怎么做到的:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 2 {
       //create and return header view
    }
    return UIView(frame: CGRect(x: 0, y:0, width: tableView.width, height: UIScreen.main.scale))
}

行为 2: TableViewCells 不应有分隔符。但是,部分应该用细线分隔。 (类似于tableviewcell分隔符)

我尝试了什么:

None 人成功了。

我是怎么做到的:

  1. 找到每个部分的最后一个单元格,
  2. 创建一个高度为 1px、tableView 宽度为 1px 的 UIView,并将其作为子视图添加到最后一个单元格

虽然这似乎有效。我觉得,必须有更好的方法来执行此操作,而不是在每个部分的最后一个 tableView 单元格的底部添加行。有谁知道实现这种行为的更好方法吗?

根据需要使用 heightForHeaderInSection 方法 UITableViewDelegate 和 return 截面高度

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 1 // return height as per your requirement
        }
        return 0 // return height as per your requirement
    }

这应该适用于在第 3 部分添加 "section separator lines" 和头部视图

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // if it's the 3rd section, return a view with desired content for the section header
    if section == 2 {
        let v = UIView(frame: CGRect(x: 0, y:0, width: tableView.frame.width, height: 30))
        v.backgroundColor = .yellow
        let label = UILabel(frame: CGRect(x: 8.0, y: 4.0, width: v.bounds.size.width - 16.0, height: v.bounds.size.height - 8.0))
        label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        label.text = "Header for Third Section"
        v.addSubview(label)
        return v
    }
    // not the 3rd section, so don't return a view
    return nil
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    // if it's the 3rd section
    if section == 2 {
        return 30
    }
    return 0
}

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    // UIView with darkGray background for section-separators as Section Footer
    let v = UIView(frame: CGRect(x: 0, y:0, width: tableView.frame.width, height: 1))
    v.backgroundColor = .darkGray
    return v
}

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    // Section Footer height
    return 1.0
}

将 Table 视图的样式设置为 Grouped

这个的简单解决方案只需在页脚视图的tableview.Set高度内添加页脚视图即可成为特定高度。

Swift:

 public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = UIColor.grey
    return view
}

public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 10
}