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

3

5

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.

Funchal answered 30/4, 2016 at 23:31 Comment(0)
A
5

Small gotcha - in Swift 3 it's

func scrollViewDidScroll(_ scrollView: UIScrollView)

and the below is not going to be triggered :

func scrollViewDidScroll(scrollView: UIScrollView)
Adulterant answered 12/10, 2016 at 16:22 Comment(0)
A
14

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.

Acquaintance answered 30/4, 2016 at 23:35 Comment(1)
Be careful with what you do in this method as it is called on every frame, though.Yerkovich
A
5

Small gotcha - in Swift 3 it's

func scrollViewDidScroll(_ scrollView: UIScrollView)

and the below is not going to be triggered :

func scrollViewDidScroll(scrollView: UIScrollView)
Adulterant answered 12/10, 2016 at 16:22 Comment(0)
S
1

You can get First and Last INDEX of visible UITableView item by using function below

This function also update itself every time when you scroll (Real time)

func scrollViewDidScroll(_ scrollView: UIScrollView){
    //First Visible Item
    print(tableView.indexPathsForVisibleRows?.first)

    //Last visible item
    print(tableView.indexPathsForVisibleRows?.last)
}
Settee answered 11/11, 2019 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.