I want to implement infinite scrolling with UICollectionView
.
//detect the bottom and add new data
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if(scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.bounds.size.height)) {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
NSLog(@"%s",__PRETTY_FUNCTION__);
//ensure that the end of scroll is fired.
[self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:nil afterDelay:0.3];
}
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
currentPage+=1;
// First figure out how many sections there are
NSInteger lastSectionIndex = [self.collectionView numberOfSections] - 1;
NSInteger lastItemIndex = [self.collectionView numberOfItemsInSection:lastSectionIndex] - 1;
NSIndexPath *pathToLastItem = [NSIndexPath indexPathForItem:lastItemIndex inSection:lastSectionIndex];
[Flickr searchFlickrForTerm:_searchBar.text page:currentPage completionBlock:^(NSString *searchTerm, NSArray *results, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.searchResults[searchTerm] addObjectsFromArray:results];
[self.collectionView reloadData];
[_collectionView scrollToItemAtIndexPath:pathToLastItem atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
});
}];
}
The problem is that scrollViewDidEndScrollingAnimation
is triggered each time when method scrollToItemAtIndexPath:
executes. As a result, I see a continuos slideshow.
I tried to used dispatch_after
with different delay, but it doesn't help.
As I understand, scrollView doesn't update it's contentSize
after [self.collectionView reloadData];
How to fix it?
Just use SVPullToRefresh which has built-in infinite scrolling. Since SVPullToRefresh is built on top of UIScrollView
, it works for anything else that is also built on top of UIScrollView
like a UITableView
or UICollectionView
.