Reputation: 353
I knew how to check the direction using scroll view delegate methods. But unfortunately, I have a situation where I have to do the same in UICollectionViewFlowLayout but I can't access with scroll view delegate methods. I tried the ways to check(inside custom layout) in which direction collection view is scrolling, but there was no luck. Please help me in this case.
Further more details: I want to check the condition inside the custom layout. If the scroll direction is vertical. I want to find is it going top or bottom.
Upvotes: 0
Views: 2002
Reputation: 748
Without any protocols or without UIScrollViewDelegate
. You can use this in your custom UICollectionViewFlow.
Enum for better code
enum ScrollDirection {
case left
case right
}
And then the function itself which you can use anytime
func getScrollDirection() -> ScrollDirection? {
guard let collectionView = collectionView else { return nil }
let scrollVelocity = collectionView.panGestureRecognizer.velocity(in: collectionView.superview)
if (scrollVelocity.x > 0.0) {
return .right
} else if (scrollVelocity.x < 0.0) {
return .left
} else {
return nil
}
}
The function may return nil in some cases so be sure to check it if needed
Use like this
if getScrollDirection() == .left
Upvotes: 3
Reputation: 72450
Add one method with your CustomFlowLayout
and with scrollViewDidScroll
method call it.
class CustomFlowLayout: UICollectionViewFlowLayout {
var currentScrollDirection = ""
func currentScroll(direction: String) {
currentScrollDirection = direction
}
}
Now implement scrollViewDidScroll
method with your ViewController
and call the currentScroll
method with CustomFlowLayout
.
var lastContentOffset = CGPoint.zero
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentOffset = scrollView.contentOffset
var scrollDirection = (currentOffset.y > self.lastContentOffset.y) ? "Down" : "Up"
if let flowLayout = collectionView.collectionViewLayout as? CustomFlowLayout {
flowLayout.currentScroll(direction: scrollDirection)
}
self.lastContentOffset = currentOffset
}
Upvotes: 1