UICollectionView实现无限滚动(理解花了我不少时间)

来源:互联网 发布:appstore付费软件 编辑:程序博客网 时间:2024/04/30 12:16

第一步:

//程序一开始就滚动到第二个cell

//滚动的前提是已经有cell数据了(所以不要在数据还没有加载就滚动)

NSIndexPath *idxPath = [NSIndexPathindexPathForItem:1inSection:0];

[self.collectionViewscrollToItemAtIndexPath:idxPath atScrollPosition:0 animated:NO];

 

第二步:

//增加一个属性,表示当前图片的索引

@property (nonatomic,assignNSInteger currentIndex;

 

//停止滚动(减速)的时候调用该方法

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    

    //获取滚动了多少个cell大小(因为滚动前cell就偏移了一个cell的距离,所以实际cell滚动的大小要减去一)

    NSInteger offset = scrollView.contentOffset.x/ scrollView.bounds.size.width - 1;

    //当前(上一个当前)图片的索引加上滚动的大小就是滚动后图片的索引(也就是最新的currentIndex

    self.currentIndex = (self.currentIndex + offset +self.headlines.count) %self.headlines.count;

    

// cell.headline = self.headlines[index];这段代码的内部是异步执行的(加载网络图片),所以把下面的代码放在主队列中,等主线程上的代码执行完毕之后再执行.

    dispatch_async(dispatch_get_main_queue(), ^{

        // 当滚动结束后,让第一个cell再偷偷的(无动画)滚回界面

        // 所以还会自动执行返回cell的方法

       NSIndexPath *idxPath = [NSIndexPath indexPathForItem:1 inSection:0];

        [self.collectionViewscrollToItemAtIndexPath:idxPath atScrollPosition:0 animated:NO];

    });

   

}

 

第三步:

//要显示多少个cell,当前方法将被调用多少次(所以当前程序第一次启动时也要调用一次)

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewcellForItemAtIndexPath:(NSIndexPath*)indexPath {

    HMHeadlineCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headline"forIndexPath:indexPath];

    

    //(当然在程序刚进来的时候,item1

    

    //1. 这里不能使用self.currentIndex表示下一个图片的索引,否则会出现拖动的时候下一张图片和当前图片相同.

    //2. 当图片一个一个滚动的时候,currentIndex在变化,下一个图片不是在currentIndex的基础上+1,就是在currentIndex的基础上-1;而在图片一个一个滚动的过程中,indexPath.item的值不是0就是2,如果给item-1的话,item-1的结果不是-1就是1,所以计算下一个图片的索引可以使用 currentIndex + item - 1

    //3. 当图片快速滚动的时候,currentIndex没有发生变化,但是item值不会只是02了,它会随着快速滚动图片的个数而发生变化(递增或者递减),item-1的值也不会只是-1或者1了;但是注意,当我们快速滚动的时候,这个方法会被连续调用,所以item-1可能表示的是下一个图片,也可能表示的是下下个图片,所以使用currentIndex + item - 1也是可行的。

    

    //4. 为了在图片滚动的时候不越界,所以加上self.headlines.count,再对self.headlines.count取余

    NSInteger index = (self.currentIndex + indexPath.item-1 + self.headlines.count)%self.headlines.count;

    

    cell.headline =nil;

    

    //下一个模型数据赋给cell

    cell.tag = index;

    cell.headline =self.headlines[index];

    

    return cell;

}

0 0