iOS tableView reloadData后上下偏移

2022-02-10  本文已影响0人  gale_小米
image.png

在网上查过多种方式都试过,但是还是没有效果
网络方式1(无效)

       self.dateTableView.tableFooterView = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        self.dateTableView.tableHeaderView = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
       self.dateTableView.estimatedRowHeight = 0;
       self.dateTableView.estimatedSectionFooterHeight = 0;
        self.dateTableView.estimatedSectionHeaderHeight = 0;

网络方式2(无效)

    //TableView 刷新后,出现偏移或抖动的现象
    var cellHeights = [IndexPath: CGFloat]()

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row  == tableView.indexPathsForVisibleRows?.last?.row  {
            DispatchQueue.main.async {
                //print("-----willDisplay-----")
                self.dateTableView.setContentOffset(CGPoint(x: 0, y: -1), animated: false)
            }
        }
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        //print("estimatedHeightForRowAt = \( cellHeights[indexPath] )")
        return cellHeights[indexPath] ?? UITableView.automaticDimension
    }

后续用了一种取巧的方式记录reloadData次数,当reloadData次数大于1时给tableview添加一个headerView把view顶下来;

......
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.reloadDataNum <= 1 {
            return 0
        }
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0{
            if self.reloadDataNum > 1 {
                let headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
                return headerView
            }
        }
        return nil
    }
......
上一篇 下一篇

猜你喜欢

热点阅读