关于 UICollectionView 的无限轮播及卡顿解决办法

2018-03-27  本文已影响443人  你也想起舞吧
lunbo.gif

思路

22.png

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _urls.count * 2;
}

滚动到第1组(下标)

dispatch_async(dispatch_get_main_queue(), ^{     
    NSIndexPath *index = [NSIndexPath indexPathForItem:_urls.count inSection:0];
    [self scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}
ps:必须要等上面所写的第一一个方法执行完后才执行这两行代码,否则数组下标溢出。所以放在主线程上异步执行。

*当 滚动到第一组 cell 最后一张时,或者第0组的第0张图片时

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  //currentPage
  NSInteger offset = scrollView.contentOffset.x / self.bounds.size.width;
  if (offset == 0 || offset == [self numberOfItemsInSection:0] - 1) {
      //NSLog(@"%ld",offset);
      offset = offset == 0? _urls.count : _urls.count - 1;
      //第一组 cell 的最后一张,则跳转到第0组的最后一张
      //第0组的第0张图片,则跳转到第1组的第0张图片
  }
  scrollView.contentOffset = CGPointMake(offset * scrollView.bounds.size.width, 0);
}

注意:

当用户快速快速切换图片时,有时会造成界面卡顿,这是因为图片跳到最后一张时要做 contentOffset 的切换,导致用户交互不良。解决办法是适当增大数据源(不必担心内存问题,UICollectionView替我们很好的解决了复用的问题)。附demo地址
上一篇 下一篇

猜你喜欢

热点阅读