Friday, February 15, 2019

How to detect if a UITableView has scrolled to the bottom

Concepts


A UIScrollView is a view whose origin (original coordinate) is adjustable over its content view. It clips the content view to its frame and changes its origin according to the finger movements. Then, the content view draws the part of itself based on the new origin.



UITableView is a subclass of UIScrollView so it's scrollable by default. To be able to detect if the scrollview has reached the bottom of its content, we have to understand three properties: contentOffset, frame, and contentSize.

contentOffset is the distance in points between the content view's origin and the scroll view's origin. A view's frame defines its location and size within its superview's coordinate system.




Codes


The ViewController must conform to UIScrollViewDelegate protocol, and set it as the tableView's delegate in viewDidLoad() method:

tableView.delegate = self
 

After that, add below method to the ViewController.
    
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
    if scrollView.frame.size.height >= scrollView.contentSize.height - scrollView.contentOffset.y {
       // add some codes here
    }
}
 

scrollView.frame.size.height does not change at all in this case. scrollView.contentSize is the size of all cells together in the table view.


References









No comments:

Post a Comment