はじめに
・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の高さがうまくキャッシュされない。