Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scrolling to an end of an horizontal UICollectionView

do you know a way in order to detect when a user has scrolled to the end (or the beginning) of an UICollectionView (in order to load new content). Since the UICollectionView scrolls horizontally and not vertically, I am not interested to the scrolling to top/bottom but to leftmost/rightmost.

The only way I found so far is to subclass the UICollectionView and then register the view controller as a delegate that is informed of when the collection view willLayoutSubviews and perform calculations accordingly.

But let's say I don't want to subclass UICollectionView, is there a way to detect the scrolling to the end/beginning of UICollectionView?

EDIT: since UICollectionView inherits from UIScrollView, I can use its delegate methods. How does it work with with horizontal scrolling?

Thank you

like image 953
maggix Avatar asked Jun 15 '14 15:06

maggix


2 Answers

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat contentWidth = scrollView.frame.size.width;

    NSLog(@"offset X %.0f", offsetX);
    // If your UICollectionView has 3 cell, the contentWidth is 320,
    // When you scroll from beginning to end of the UICollectionView, it will print:
    // offset X 0
    // offset X 1
    // offset X 2
    // ......
    // offset X 320
    // offset X 640
}
like image 176
li2 Avatar answered Oct 18 '22 21:10

li2


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[UICollectionView class]] == YES) {
        CGFloat threshold = 100.0 ;
        CGFloat contentOffset = scrollView.contentOffset.x;
        CGFloat maximumOffset = scrollView.contentSize.width - scrollView.frame.size.width;
        if ((maximumOffset - contentOffset <= threshold) && (maximumOffset - contentOffset != -5.0) ){
            //Your code
        }
    }
}
like image 40
Torongo Avatar answered Oct 18 '22 21:10

Torongo