使用UICollectionView无限滚动

时间:2013-06-07 12:53:30

标签: objective-c ios6 uicollectionview

我想用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];
        });
    }];

}

问题是每次执行方法scrollViewDidEndScrollingAnimation时都会触发scrollToItemAtIndexPath:。结果,我看到了连续幻灯片。

我尝试使用不同延迟的dispatch_after,但它没有帮助。

据我了解,在contentSize

之后,scrollView不会更新它[self.collectionView reloadData];

如何解决?

1 个答案:

答案 0 :(得分:3)

只需使用内置无限滚动的SVPullToRefresh即可。由于SVPullToRefresh建立在UIScrollView之上,因此它适用于UIScrollView之上构建的任何其他内容,例如UITableViewUICollectionView

https://github.com/samvermette/SVPullToRefresh/