iOS tableview how can I check if it is scrolling up or down iOS tableview how can I check if it is scrolling up or down swift swift

iOS tableview how can I check if it is scrolling up or down


Like @maddy said in the comment of your question, you can check if your UITableView is scrolling by using the UIScrollViewDelegate and further more you could check which direction it scrolls to by using both scrollViewDidScroll and scrollViewWillBeginDragging functions

// we set a variable to hold the contentOffSet before scroll view scrollsvar lastContentOffset: CGFloat = 0// this delegate is called when the scrollView (i.e your UITableView) will start scrollingfunc scrollViewWillBeginDragging(_ scrollView: UIScrollView) {    self.lastContentOffset = scrollView.contentOffset.y}// while scrolling this delegate is being called so you may now check which direction your scrollView is being scrolled tofunc scrollViewDidScroll(_ scrollView: UIScrollView) {    if self.lastContentOffset < scrollView.contentOffset.y {        // did move up    } else if self.lastContentOffset > scrollView.contentOffset.y {        // did move down    } else {        // didn't move    }}

Furthermore: You don't need to subclass your UIViewController with UIScrollViewDelegate if you've already subclassed your UIViewController with UITableViewDelegate because UITableViewDelegate is already a subclass of UIScrollViewDelegate


You can implement scrollViewWillEndDragging method:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {    if targetContentOffset.pointee.y < scrollView.contentOffset.y {        // it's going up    } else {        // it's going down    }}


first we should make two property for last Offset and Current Offset

 var lastOffset = CGFloat() var currentOffset = CGFloat()

then in the Scrollview VC call the scrollViewWillBeginDragging for get current offset

 override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {        self.lastOffset = scrollView.contentOffset.y    }

and scrollViewWillBeginDecelerating for get last offset

    override func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {        self.lastOffset = scrollView.contentOffset.y        viewStatus(scrollView: scrollView)    }

then with this two variable you can know your scrollview Where it goes‍‍‍‍

‍‍‍let isScrollUp = scrollView.contentOffset.y > self.lastOffsetlet isScrollDown  = scrollView.contentOffset.y < self.lastOffset