[iOS] UITableView에서 estimatedRowHeight를 사용. reloadData하면 위치가 어긋날 때 해결방법

오준석·2019년 1월 7일
3

UITableView의 아이템들의 높이가 다를 때 reloadData하면 스크롤 위치가 엉뚱한 곳으로 점프한다.

검색 해 보면 스크롤 위치를 저장, 복원하는 별의별 방법이 있는데 다 필요없고
이럴 때는 미리 계산된 셀들의 높이를 저장해 두고 복원하는 방법이 가장 간단한 듯 하다.

엄청난 삽질을 했기 때문에 기록 해 둔다.

var cellHeightsDictionary: NSMutableDictionary = [:]
...
// save height
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeightsDictionary.setObject(cell.frame.size.height, forKey: indexPath as NSCopying)
}

// height value 복원
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    if let height = cellHeightsDictionary.object(forKey: indexPath) as? Double {
        return CGFloat(height)
    }
    return UITableView.automaticDimension
}
profile
교육하고 책 쓰는 개발자

2개의 댓글

comment-user-thumbnail
2021년 9월 5일

선생님... 감사합니다. 며칠동안 고민했던 문제였는데 고맙습니다! 더 좋은 방법 찾으면 댓글 다시 달겠습니다 !

1개의 답글