brunch

You can make anything
by writing

C.S.Lewis

by 오준석 Jan 07. 2019

[iOS] UITableView 리로드시 스크롤 위치

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
}


동일한 포스팅을 velog에도 하고 있습니다. 코드 복사등이 용이합니다.

https://velog.io/@jsoh/iOS-UITableView%EC%97%90%EC%84%9C-estimatedRowHeight%EB%A5%BC-%EC%82%AC%EC%9A%A9.-reloadData%ED%95%98%EB%A9%B4-%EC%9C%84%EC%B9%98%EA%B0%80-%EC%96%B4%EA%B8%8B%EB%82%A0-%EB%95%8C-%ED%95%B4%EA%B2%B0%EB%B0%A9%EB%B2%95

매거진의 이전글 [iOS] 키보드가 나타나면 TextField 이동

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari