나의 발자취

iOS 무한 스크롤 구현하는 법: How to implement an Infinite Scrolling List 본문

앱 개발/iOS

iOS 무한 스크롤 구현하는 법: How to implement an Infinite Scrolling List

달모드 2024. 9. 16. 12:00

구현 방법

1. data source를 반영해서 보여주는 UITableView에서 테이블 뷰 셀을 만든다.

2. UITableViewDelegate의 scrollViewDidScroll 메서드를 가지고와서, 유저가 테이블 뷰의 제일 하단으로 스크롤을 했을 때 감지할 수 있도록 한다.

3. 유저가 테이블뷰의 제일 하단에 닿았을 때, 데이터를 더 가지고 와서 현존하는 data source에 추가해서 더한다.

4. reloadData 로 새로운 데이터를 가져온 테이블뷰를 업데이트해서 디스플레이한다.

 

code snippet

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    
    if offsetY > contentHeight - scrollView.frame.height {
        // The user has scrolled to the bottom of the table view.
        // Load more data here.
        loadMoreData()
    }

    func loadMoreData() {
        // Load more data here and append it to your existing data source.
        let newData = fetchNextBatchOfData()
        dataSource.append(contentsOf: newData)
        
        // Reload the table view with the updated data source.
        tableView.reloadData()
    }

 

 

무한 리스트의 스크롤링 퍼포먼스를 높이는 방법

1. Load data incrementally - 전체 데이터를 한번에 로딩하는 대신, 작은 batches로 나누어서 메모리 overhead를 줄이고 성능을 높인다.

2. Reuse table view cells - dequeueReusableCellWithIdentifier 를 써서 각 row마다 새로운 셀을 생성하는 대신 재사용한다. (이것 역시 메모리 overhead를 줄이고 성능을 높임)

3. Cache images and other resources - 만약 테이블뷰가 이미지같은 리소스를 포함한다면, 캐싱을 한다.

4. Use lazy loading - 필요할때만 데이터를 로드하고, 그 전에는 로드하지 않는다. 

5. Avoid blocking the main thread - 데이터를 로딩하는 것은 time-consuming일 수 있다. 그래서 메인 쓰레드를 블라킹하는걸 피하는게 중요하다. 데이터 로딩과 프로세싱을 할 때는 background threads를 사용하고, UI 업데이트를 할 때에 메인 쓰레드를 사용한다.

 

 

출처: cracking the ios interview

Comments