Ricky Geng
Ricky Geng

Reputation: 187

Scroll action on tableview

I'm using this function to detect if a up/down scroll action is applied on tableView. For some reason, it only detects scroll up but not down. Any ideas?

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    tableView.reloadData()

    DispatchQueue.main.async {

        if targetContentOffset.pointee.y < scrollView.contentOffset.y {
            print("go up")
            print(self.currentRow)
            self.tableView.scrollToRow(at: NSIndexPath(row: self.currentRow-1, section: 0) as IndexPath, at: UITableView.ScrollPosition.top, animated: true)

        } else {
            print("go down")
            print(self.currentRow)
            self.tableView.scrollToRow(at: NSIndexPath(row: self.currentRow+1, section: 0) as IndexPath, at: UITableView.ScrollPosition.top, animated: true)
            self.currentRow += 1
        }
    }
}

Upvotes: 0

Views: 406

Answers (2)

ctrl freak
ctrl freak

Reputation: 12405

Simply keep a record of the last offset outside of the scrollViewDidScroll delegate and check if the current offset is greater than or less than that value.

var lastOffset: CGFloat = 0

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let offset = scrollView.contentOffset.y

    if offset < lastOffset { // check offset difference
        NSLog("user is scrolling up")
    } else {
        NSLog("user is scrolling down")
    }
    lastOffset = offset // record last offset

}

I used NSLog to print to console to add a timestamp so that you can see it fire on long scrolls.

Upvotes: 1

KingHodor
KingHodor

Reputation: 547

scrollViewWillEndDragging tells the delegate when the user finishes scrolling the content.

Try to use this function:

 var current:CGFloat = 0
 func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    self.current = scrollView.contentOffset.y
 }

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let contentOffset = scrollView.contentOffset.y
    if contentOffset > current {
        print("go up")
    }else if current > contentOffset{
        print("go down")
    }else{//
    }
 }

Upvotes: 1

Related Questions