How to know if UITableView is being scrolled manually (by hand) or programmatically?

Viewed 9061

I am using a UITableView in my code and it would be nice to know if the user manually scrolled the UITableView or it was done programmatically. Is there a way to know that?

6 Answers

Best method I've found is to use the isTracking property rather than isDragging.

if tableView.isTracking && tableView.isDecelerating {
    // Table was scrolled by user.
}

Use this to detect both fast and slow scrolling caused by user interaction:

if tableView.isDragging, tableView.isDecelerating || tableView.isTracking {
    // Table view is scrolled by user, not by code
}

I checked tableView.isTracking and tableView.isDecelerating inside scrollViewDidScroll. However, it didn't work for me if the user only slightly moved the tableview. Since a scrollView has a panGesture we can check the velocity of that gesture. If the tableView was programmatically scrolled the velocity in both x and y directions is 0.0. By checking this velocity we can determine if the user scrolled the tableView because the panGesture has a velocity.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let velocity = scrollView.panGestureRecognizer.velocity(in: tableView)
    print("Velocity: \(velocity)")
    if velocity.x != 0.0 || velocity.y != 0.0 {
        // user scrolled the tableview
    }
}
Related