본문 바로가기
Programming/Swift

[Readable Coding Practice] UIScrollView Pagination

by Eisen Sophie 2021. 6. 19.

When you are working with REST API and and pulling out data from it, you sometimes cannot take all of the data down to your VC.

 

In this case, by using pagination, you can show the data page by page.

 

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let offsetY     = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let height        = scrollView.frame.size.height
        
        if offsetY > contentHeight - height {
            if hasMoreFollowers {
                page += 1
                getFollowers(username: username, page: page)
            }
        }
    }

 

offsetY variable changes its value as the user scrolls the screen vertically.

When the user scroll down, its value increase and down for vice versa.

 

contentHeight represents a total height of the scrollView.

If there are a lot of contents to show on the scrollView, then there will be larger value for this variable.

 

height is the height of the view that the user is looking at. This varies among the different phone size.