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

前端 未结 3 956
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 20:20

I am learning how to work with TableViews and I am wondering how can I figure out if the tableView is scrolling up or down ? I been trying various things such as this but it

3条回答
  •  时光说笑
    2020-12-13 20:32

    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 scrolls
    var lastContentOffset: CGFloat = 0
    
    // this delegate is called when the scrollView (i.e your UITableView) will start scrolling
    func 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 to
    func 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

提交回复
热议问题