0

I have UICollectionView in my ViewController (Please check below attached image for view hierarchy). How can we detect when the user swipes up or down?

It doesn't matter if we add gesture recognizer to UIView or UICollectionView. I just want to know the swipe gesture.

View Hierarchy

I've tried adding gesture recognizer to UIView and UICollectionView by using codes in stack overflow. But none of them satisfied my requirement.

Thanks in advance.

Nirav Kotecha
  • 2,493
  • 1
  • 12
  • 26
Eswar
  • 199
  • 1
  • 13
  • This is too broad. What have you tried so far? What is the specific roadblocks you are running into? What error are you getting? What is not working? – Andreas Jun 28 '19 at 05:29
  • You don't need any gesture reco. Collection view is inherits UIScrollview so you can set delegate of collectionview to self and implement UIScrollViewDelegate methods – Prashant Tukadiya Jun 28 '19 at 05:29
  • @Andreas - i have tried adding UISwipeGestureRecognizer() to UIView and UICollectionView. No error has been raised. but didn't get desired result. please refer this link for my issue related to this question - "** https://stackoverflow.com/questions/56787905/material-floating-action-button-should-invisible-when-user-scroll-down-and-visib/56788054?noredirect=1#comment100131775_56788054 **" – Eswar Jun 28 '19 at 05:34
  • @PrashantTukadiya - even i did that what you have suggested. Please refer this link for exact issue related to my question here - "** https://stackoverflow.com/questions/56787905/material-floating-action-button-should-invisible-when-user-scroll-down-and-visib/56788054?noredirect=1#comment100131775_56788054 **" – Eswar Jun 28 '19 at 05:38
  • 1
    There are many questions that talks about how to detect the direction in which the user has scrolled a scroll view, such as [this](https://stackoverflow.com/questions/14042203/detect-direction-of-uiscrollview-scroll-in-scrollviewwillbegindragging/16964554) and [this](https://stackoverflow.com/questions/2543670/finding-the-direction-of-scrolling-in-a-uiscrollview/26192103). They should help/ – Sweeper Jun 28 '19 at 05:46

1 Answers1

1

Since collectionView is a basically a scrollView, use scrollViewDidScroll(_:) method to identify the scrolling direction of the collectionView.

private var lastContentOffset: CGFloat = 0.0

In the above code, lastContentOffset keep track of the previous contentOffset of the collectionView while scrolling.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y < self.lastContentOffset) {
        //Scrolling up
    }
    else if (scrollView.contentOffset.y > self.lastContentOffset) {
        //Scrolling down
    }
    self.lastContentOffset = scrollView.contentOffset.y
}

Don't forget to conform to UICollectionViewDelegate protocol.

Also, there is no need for adding any separate gestureRecognizer. UICollectionView being a UIScrollView will handle it on its own.

PGDev
  • 23,751
  • 6
  • 34
  • 88