iOS界面特效篇iOS DeveloperiOS第三方资料收集

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

2016-10-25  本文已影响1662人  江水东流

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

无限图片轮播demo github地址 https://github.com/1271284056/Unlimited-images-player

瀑布流 demo github地址 https://github.com/1271284056/Waterfall-flow

效果图如下

瀑布流.gif
实现图片无限轮播的主要思路图如下
屏幕快照 2016-10-25 10.17.36.png
  • (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;
    }

瀑布流具体实现如下

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
/**

/**

/**

pragma 核心代码

//找出高度最短的那一列
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;

}

//整体的高度

上一篇 下一篇

猜你喜欢

热点阅读