Reputation: 199
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.
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.
Upvotes: 0
Views: 960
Reputation: 24341
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.
Upvotes: 1