美文网首页
UITableView 为 Grouped 类型时设置 tabl

UITableView 为 Grouped 类型时设置 tabl

作者: AndyGF | 来源:发表于2020-08-28 11:38 被阅读0次

今天遇到一个 bug, 用 grouped 的方式创建的 tableView, 再配合上 组头 和 组尾的使用, tableHeaderView 的 y 值默认有 35 的向下偏移.

   private lazy var header: UIView = {
        let v = UIView(frame: .zero)
        return v
    }()
    
    private lazy var tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .grouped)
        tv.backgroundColor = .gray
        tv.separatorStyle = .none
        tv.estimatedRowHeight = 35
        tv.rowHeight = UITableView.automaticDimension
        tv.showsVerticalScrollIndicator = false
        tv.tableHeaderView = header
        tv.delegate = self
        tv.dataSource = self
        tv.register(SHWWorkPartListCell.self, forCellReuseIdentifier: SHWWorkPartListCellID)
        return tv
    }()

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = UIView(frame: .zero)
        header.backgroundColor = .red
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView(frame: .zero)
        footer.backgroundColor = .green
        return footer
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10.0
    }

最终解决办法是改变 header 的初始化 , 高度绝对值大于 0.1 就可以, 亲测 -1 可以,


    private lazy var header: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 0, height:  GFloat.leastNormalMagnitude))
        return v
    }()

// 或者

    private lazy var header: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 1))
        return v
    }()

CGFloat.leastNormalMagnitude 对应 OC 是 CGFLOAT_MIN

高度问题, 设置为 1, 100, 这样的数, 由于机型和系统版本不多, 我测试用的 6sp, 是可以的, 所以兼容性问题不确定, 不能保证每个通用, leastNormalMagnitude / CGFLOAT_MIN 是大家都在用的. 应该没什么问题, 具体还要以实际效果为准.

相关文章

网友评论

      本文标题:UITableView 为 Grouped 类型时设置 tabl

      本文链接:https://www.haomeiwen.com/subject/ghxlsktx.html