LoginSignup
6
6

More than 5 years have passed since last update.

TableViewのreloadData()後レイアウトがズレる(カクカク)改善メモ

Posted at

はじめに

・tableViewをページングする際にreloadData()を行うとtableViewがカクカクする現象
・tableViewのestimatedHeightForRowAt:の設定でハマっていいたのでメモ
・ページングした時にtableViewHeightの見積もりが合わない,または更新されない場合に発生

確認すること

tableViewの見積もりにより、正確な高さを取得できなくて(間に合わず)発生するのでestimatedHeightForRowAtを設定。
固定cellなのでreturn UITableView.automaticDimensionで自動で高さを見積もればいいと思っていましたが、tableViewのindexPathでcellの高さを計算した方がtableViewの動きがよくなりました。また、estimatedHeightForRowAtは更新の時に逐一呼ばれるので、UITableView.automaticDimensionだとtableViewCellの見積もりを再計算しなおすので効率が悪くカクカクの原因になってしまう。とういうことで記述

tableView.swift
var cellHeight: [IndexPath: CGFloat] = [:]

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let cellHeight = self.cellHeight[indexPath] else {
            //取得できなかった場合に自動計算
            return UITableView.automaticDimension
        }
        return height
    }
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if self.cellHeightList.keys.contains(indexPath) != true {
            self.cellHeightList[indexPath] = cell.frame.height
        }
    }

最後に

tableViewの更新などを行う場合は、cellHeight辞書のクリアを忘れずに行わないとcellの高さがうまくキャッシュされない。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6