UITableView 调整 Header 层级关系

UITableView 的 Header如何嵌在第一个 Cell 下面
为什么要调整层级关系

还用问嘛,当然是产品经理拿着四十米大刀告诉你我就要这个效果。

在这里插入图片描述

橙色 View 为轮播滚动效果。

一眼看过去,简单,就是 tableView + 一个 headerView

思路

让 headerView 的子视图比 Header高一点,就可以超出 headerView 占位高度,达到在第一个 Cell 的底部,完成 UI 小姐姐的交叉效果。

一顿猛操作

   private func setupTableView() {
        tableView.tableHeaderView = tableViewHeader()
        tableView.rowHeight = UITableView.automaticDimension
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "Cell")
        self.view.addSubview(tableView)
    }
    
    private func tableViewHeader() -> UIView {
        header = UIView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200))
        let contentView = UIView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 220))
        header.addSubview(contentView)
        contentView.backgroundColor = .orange
        return header
    }

一看效果真是虎

在这里插入图片描述

发现HeaderView遮挡了第一个 Cell,

说明 HeaderView 在 第一 Cell 之后渲染的,所以只要让 HeaderView 的层级调低,让它后渲染就可以完成了。

于是在setupTableView()中添加如下方法

private func setupTableView() {
    tableView.tableHeaderView = tableViewHeader()
    tableView.sendSubviewToBack(header) 
    ...
}

运行之后发现还是被遮挡,没有效果, tableView 渲染时还是会在第一个 cell 的上面,猜测是不是 tableView 内部调整了的。

终极办法

在 UITableViewDelegate willDisplay cell代理方法中设置

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == 0 { // 在第一行情况下, 将header调整到最底层。
            tableView.sendSubviewToBack(header)
        }
    }

完美调整图层渲染,达成效果

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值