Use Threshold for preloading

ContentView = uitableView.contentView = uitableView.contentView = uitableView.contentView

Let threshold: CGFloat = 0.7 var currentPage = 0 Override func scrollViewDidScroll(_ scrollView: UIScrollView) { let current = scrollView.contentOffset.y + scrollView.frame.size.height let total = scrollView.contentSize.height let ratio = current / total if ratio >= threshold { currentPage += 1 print("Request page \(currentPage) from server.") } }Copy the code

The code above requests new resources, data, when the current page is 70% crossed; However, there is another problem with using this method alone, especially when the list becomes very long, such as when the user swipes down and loads a total of five pages of data:

When the Threshold is set to 70%, it is not a single page 70%, which will result in the newly loaded page is not seen, and the application will issue another request for new resources.

Dynamic Thres

The solution to this problem is simple: change Threshold to a dynamic value that increases as the number of pages increases:

Let threshold: CGFloat = 0.7 let itemPerPage: CGFloat = 10 var currentPage: CGFloat = 0 override func scrollViewDidScroll(_ scrollView: UIScrollView) { let current = scrollView.contentOffset.y + scrollView.frame.size.height let total = scrollView.contentSize.height let ratio = current / total let needRead = itemPerPage * threshold + currentPage * itemPerPage let totalItem = itemPerPage * (currentPage + 1) let newThreshold = needRead / totalItem if ratio >= newThreshold { currentPage += 1 print("Request page \(currentPage) from server.") } }Copy the code