z2k
z2k

Reputation: 10410

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{

Upvotes: 4

Views: 4640

Answers (2)

Aouiaiauo Eyjaajeyio
Aouiaiauo Eyjaajeyio

Reputation: 346

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")
}

Upvotes: 10

Saleh Albuga
Saleh Albuga

Reputation: 448

Also you can use this:

CGPoint translation = [collectionView.panGestureRecognizer translationInView:collectionView.superview];
        if (translation.y > 0) {
            NSLog(@"DOWN");
        } else {

            NSLog(@"UP");
        }

More accurate

Upvotes: 0

Related Questions