简体   繁体   中英

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{

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

Also you can use this:

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

            NSLog(@"UP");
        }

More accurate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM