Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active September 3, 2021 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/0a94ac776725789f4857743540a60bbf to your computer and use it in GitHub Desktop.
Save TuenTuenna/0a94ac776725789f4857743540a60bbf to your computer and use it in GitHub Desktop.
UIKit 테이블뷰 데이터 추가시 옵셋 유지 하고 리로드

UIKit 테이블뷰 데이터 추가시 옵셋 유지 하고 리로드

extension UITableView {
    public func reloadDataAndKeepOffset() {
        // stop scrolling
        setContentOffset(contentOffset, animated: false)
            
        // calculate the offset and reloadData
        let beforeContentSize = contentSize
        reloadData()
        layoutIfNeeded()
        let afterContentSize = contentSize
            
        // reset the contentOffset after data is updated
        let newOffset = CGPoint(
            x: contentOffset.x + (afterContentSize.width - beforeContentSize.width),
            y: contentOffset.y + (afterContentSize.height - beforeContentSize.height))
        setContentOffset(newOffset, animated: false)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment