How to get the scroll position of a UITableView in real time

TZE1000 picture TZE1000 · May 1, 2016 · Viewed 13.1k times · Source

I need to get the scroll position of a table view in real time. What I am currently doing is:

func animationOffset() {
    let offset = tableView.contentOffset.y
}

This function is connected to a timer

timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(TimelineViewController.animationOffset), userInfo: nil, repeats: true)

This code works fine if the user lifts their finger off the screen, but if they don't and keep scrolling, the offset will never be updated and my app will not run properly.

Answer

Jelly picture Jelly · May 1, 2016

You can implement

func scrollViewDidScroll(scrollView: UIScrollView)

of the UITableViewDelegate which is called when the scroll position of the tableview is changed and there you can use tableView.contentOffset.y to get scroll position.