简体   繁体   中英

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

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.

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.

Small gotcha - in Swift 3 it's

func scrollViewDidScroll(_ scrollView: UIScrollView)

and the below is not going to be triggered :

func scrollViewDidScroll(scrollView: UIScrollView)

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM