tableView 隐藏 section 分割线 并且显示 row 分割线

一般我们设置 grouped 类型的 tableView 时, 可以通过 separatorStyle 设置分割线样式有无, 有分割线的时候, 各组之间的分割线也是存在的, 比如这样:

如果需有组的分割样式, 同时还需要分割线, 但是分割线只用来分割 cell 比如这样的需求

一般这种情况大家都会设置 tableView 的 style 为 grouped, 然后自定义每个 cell 都带了分割线, 但是这个方法有个问题, 一组的最后一个 cell 是不需要显示分割线的, 需要在 cell 的代理方法去隐藏这条线或者 cell 里过滤处理, 如果有很多个组那么这样会很麻烦, 代码写的多, 也很乱.

其实还有一个更简单的方式来实现, 就是设置 tableView 的样式为 plain(默认 plain)

   lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()

然后用设置相应高度的 footerView 和 headerView, 并且设置颜色为透明, 这样就看不出来了, 要不然等键盘调用弹出后, footerView 会保留在键盘上方, 或者列表太长, headerView 会停留顶部

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

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

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
}

results matching ""

    No results matching ""