Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect direction of scrolling UICollectionView, load data from REST

Assuming standard configuration (up/down), I'd like to detect when a user is scrolling their UIColletionView up or down (which is subclass of UIScrollView and conforms to UIScrollViewDelegate). I don't see any information straight out of the delegate to detect this, although I may be over looking something.

If I know which direction the user is scrolling, then I can use these UICollectionViewDatasource methods to determine if I should load more data from the REST server, or purge information that I already have to manage fixed memory space.

// If scrolling down, section is appearing

- (UICollectionReusableView *)collectionView:(UICollectionView *)cv viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

// If scrolling down, last cell in section is disappearing

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{

// If scrolling up, last cell in section is appearing

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

// If scrolling up, section is disappearing

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
like image 218
VaporwareWolf Avatar asked Dec 27 '22 05:12

VaporwareWolf


1 Answers

You can check UIScrollView's (which UICollectionView inherits from) panGestureRecognizer property and do something like this:

CGPoint scrollVelocity = [collectionView.panGestureRecognizer velocityInView:collectionView.superview];
if (scrollVelocity.y > 0.0f) {
    NSLog(@"going down");
} else if (scrollVelocity.y < 0.0f) {
    NSLog(@"going up");
}

Swift 3.1:

let scrollVelocity = collectionView.panGestureRecognizer.velocityInView(collectionView.superview)
if (scrollVelocity.y > 0.0) {
    print("going down")
} else if (scrollVelocity.y < 0.0) {
    print("going up")
}
like image 133
Aouiaiauo Eyjaajeyio Avatar answered Jan 30 '23 22:01

Aouiaiauo Eyjaajeyio