iOS - 无限图片轮播 + 瀑布流快速实现

3,786 阅读3分钟
原文链接: www.jianshu.com

这两个都是用UICollectionView实现的,搞定这两个demo,就能掌握UICollectionView.

无限图片轮播demo github地址 github.com/1271284056/…

瀑布流 demo github地址 github.com/1271284056/…

效果图如下

  • 无限图片轮播


    无限轮播_.gif

  • 瀑布流


瀑布流.gif

实现图片无限轮播的主要思路图如下

屏幕快照 2016-10-25 10.17.36.png

  • 如果你要展示3张图片,实现无限循环滚动,你创建两组6个collectionViewCell, 初始化时候滚动到第二组的第一个cell,实现这一点需要在UICollectionView初始化时候在主队列添加滚动任务.
  • 安排任务在主线程上执行,如果主线程当前有任务,主队列暂时不调度任务!所以等cell的数据源和代理方法执行完毕后才执行这个block里面的滚动任务.一般我们开发中用到多线程有两点:1. 无限循环图片轮播器.2.异步裁剪图片,见我的另一篇文章ImageView性能测试以及优化

     dispatch_async(dispatch_get_main_queue(), ^{
    
         NSIndexPath *indexPath = [NSIndexPath indexPathForItem:_urls.count inSection:0];
    
         // 滚动位置!
         [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
     });
  • 在- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {}scrollView这个代理方法里面判断cell滚动的位置,如果滚动到最后一组最后一张,则让整体滚动到第一组最后一张.如果滚动到第一组第一张,则滚动到最后一组第一张.

    • (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
      // 1. 获取当前停止的页面
      NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width;
      // 2. 第0页,调转到,第1组的第0页
      // 最后一页,跳转到第0组的最后一页
      if (offset == 0 || offset == ([self numberOfItemsInSection:0] - 1)) {
      // NSLog(@"%zd", offset);
      // 第 0 页
      if (offset == 0) {
          offset = _urls.count;
      } else {
          offset = _urls.count - 1;
      }
      // 重新调整 contentOffset
      scrollView.contentOffset = CGPointMake(offset * scrollView.bounds.size.width, 0);
      }
      }

系统调用滚动方法时候会卡顿,在numberOfItemsInSection里面进行如下代码处理

  • (NSInteger)collectionView:(UICollectionView )collectionView numberOfItemsInSection:(NSInteger)section {
    //这里为了防止滚动到最后一页来回跳动导致的卡顿,多写点组数让一直到不了最后一组,因为cell重用,所以不影响内存.
    return _urls.count
    100;
    }

瀑布流具体实现如下

  • 关键是自定义一个WaterFlowLayout : UICollectionViewLayout类,建一个代理,控制器首先初始化WaterFlowLayout,并且遵守代理,返回cell的宽高.修改cell的UICollectionViewLayoutAttributes属性,使在布局时候每一个cell放到整体列高度最短那一列,这样的cell不是按顺序布局的.

import "WaterFlowLayout.h"
/ 默认列数 */
static const NSInteger DefaultColumnCount = 3;
/
每一列之间的间距 /
static const NSInteger DefaultColumnMargin = 10;
/*
每一行之间的间距 /
static const NSInteger DefaultRowMargin = 10;
/*
边缘间距 */
static const UIEdgeInsets DefaultEdgeInsets = {0, 0, 0, 0};

@interface WaterFlowLayout ()
/ 存放所有cell的布局属性 /
@property (nonatomic, strong) NSMutableArray
attrsArray;
/
存放所有列的当前高度 /
@property (nonatomic, strong) NSMutableArray
columnHeights;
/* 内容的高度 /
@property (nonatomic, assign) CGFloat contentHeight;
@end

@implementation WaterFlowLayout
/**

  • 初始化
    */
    • (void)prepareLayout {
      [super prepareLayout];
      self.contentHeight = 0;
      //清除以前计算的所有高度
      [self.columnHeights removeAllObjects];
      //记录每一列的高度 一共3列
      for (NSInteger i = 0; i < DefaultColumnCount; i++) {
      [self.columnHeights addObject:@(DefaultEdgeInsets.top)];
      // NSLog(@"%f",self.edgeInsets.top);
      }
      //清除之前所有布局属性
      [self.attrsArray removeAllObjects];
      //开始创建每一个cell对应发布局属性
      NSInteger count = [self.collectionView numberOfItemsInSection:0];
      for (NSInteger i = 0; i < count; i++) {
      //创建位置
      NSIndexPath indexPath = [NSIndexPath indexPathForItem:i inSection:0];
      //获取indexPath位置cell对应的布局属性
      UICollectionViewLayoutAttributes
      attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
      [self.attrsArray addObject:attrs];
      }
      }

/**

  • 决定cell的布局 prepareLayout后会调用一次,下面方法调用完毕修改cell属性后会再一次调用这个方法
    */
    • (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
      return self.attrsArray;
      }

/**

  • 返回每一个位置cell对应的布局属性 修改 self.attrsArray里面cell的属性,这个方法执行后再调用上一个方法
    */
    • (UICollectionViewLayoutAttributes )layoutAttributesForItemAtIndexPath:(NSIndexPath )indexPath {
      //创建布局属性
      UICollectionViewLayoutAttributes attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
      //collectionView的宽度
      CGFloat collectionViewW = self.collectionView.frame.size.width;
      //设置布局属性的frame
      CGFloat w = (collectionViewW - DefaultEdgeInsets.left - DefaultEdgeInsets.right - (DefaultColumnCount - 1)
      DefaultRowMargin) / DefaultColumnCount;
      CGFloat h = [self.delegate waterflowlayout:self heightForItemAtIndex:indexPath.item itemWidth:w];
//找出高度最短的那一列
NSInteger destColumn = 0;
//默认第一列最短
CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
for (NSInteger i = 0; i < DefaultColumnCount; i++) {
    //取得第i列的高度
    CGFloat columnHeight = [self.columnHeights[i] doubleValue];
    //minColumnHeight是最短那一列的高度,destColumn最短那一列
    if (minColumnHeight > columnHeight) {
        minColumnHeight = columnHeight;
        destColumn = i;
    }
}
CGFloat x = DefaultEdgeInsets.left + destColumn * (w + DefaultColumnMargin);
CGFloat y = minColumnHeight;
if (y != DefaultEdgeInsets.top) {
    y += DefaultRowMargin;
}
attrs.frame = CGRectMake(x, y, w, h);
//更新最短那列的高度
self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
//记录内容的高度
CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];
if (self.contentHeight < columnHeight) {
    self.contentHeight = columnHeight;
}
return attrs;

//整体的高度

  • (CGSize)collectionViewContentSize {
    return CGSizeMake(0, self.contentHeight + DefaultEdgeInsets.bottom);
    }