首页 > 解决方案 > UITableview 粘性标题未在 iPhone X 上正确呈现

问题描述

我在 UITableView 中有一个粘性标题,它适用于除 iPhone X 之外的所有设备。在第一次渲染时不会启动上边距(-24),只有当我开始滚动时它才会卡入应该的地方。

这是示例: 绿色是tableview的背景

这是代码:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerId) as! ArticleDetailHeader

    header.article = article
    headerView = header

    return header
}

显示标题后加载

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    updateHeaderView()
}

这是 updateHeaderView 函数

    func updateHeaderView() {

        var height = CGFloat(460)

        if ((view.frame.width * 0.56) < 459) {
            height = view.frame.width * 0.56
        }

        let offsetY = tableView.contentOffset.y

        let newOffset = -1 * offsetY
        let newHeight = (height) + newOffset

        self.lastContentDifference =  height + newOffset

        if (self.lastContentOffset > 64) {
            navigationBarTransparency(transparent: true)
        } else {
            navigationBarTransparency(transparent: false)
        }

        self.lastContentOffset = self.lastContentDifference

        headerView?.headerImage.frame = CGRect(x: 0, y: offsetY, width: tableView.frame.width, height: newHeight)
        headerView?.headerImage.layoutIfNeeded()

}

这是scrollViewdidScroll

override func scrollViewDidScroll(_ scrollView: UIScrollView) {

    isBouncing = scrollView.isBouncing

    if let tableView = scrollView as? UITableView {
        updateHeaderView()

        for cell in tableView.visibleCells {
            guard let cell = cell as? ArticleDetailPost else { continue }
            cell.webView.setNeedsLayout()
        }
    }

}

这是在我的 viewDidLoad 里面

        tableView = UITableView(frame: CGRect.zero, style: .grouped)
    tableView.backgroundColor = .white
    tableView.register(ArticleDetailHeader.self, forHeaderFooterViewReuseIdentifier: headerId)
    tableView.register(ArticleDetailPost.self, forCellReuseIdentifier: cellId)
    tableView.separatorColor = .clear        
    tableView.contentInset = UIEdgeInsetsMake(-64, 0, -40, 0)
    tableView.isScrollEnabled = true
    tableView.backgroundColor = .green

我有一种感觉,我忽略了一些非常简单的事情,但在过去的几个小时里它一直在打破我的大脑。

标签: iosiphoneuitableviewuitableviewsectionheader

解决方案


推荐阅读