[个人博客搬运]定制UICollectionViewLayout实现集合视图

最新的需求中,需要实现一个展示宝贝上新的视图,展现方式是点击一个UITableView的cell,在cell拉出一个空白的“抽屉”视图,“抽屉”中横向展示可滚动的多个宝贝的图文视图,于是很自然地想到用UICollectionView来实现。后来这个需求被砍掉了(orz),不过UICollectionView是一个很有意思很灵活的视图,类似Android的GridView,但是比之功能更强大,它可以具体到每一个item的定制,完全取决于UICollectionViewLayout的实现。

answer huang的译文中这样说明UICollectionView:

UITableView和UICollectionView都是由data-source和delegate驱动的。他们为其显示的子视图集扮演为愚蠢的容器(dumb containers),对他们真实的内容(contents)毫不知情。

UICollectionView进一步抽象了。它将其子视图的位置,大小和外观的控制权委托给一个单独的布局对象。通过提供一个自定义布局对象,你几乎可以实现任何你能想象到的布局。布局继承自UICollectionViewLayout这个抽象基类。iOS6中以UICollectionViewFlowLayout类的形式提出了一个具体的布局实现。

关于UICollectionView,其他的同事已经介绍过啦,可以看这里

我们写一个简单的小demo,效果类似这样
UICollectionViewFlowLayout

这是最简单的流水布局:UICollectionViewFlowLayout。类如其义,它提供一个流水布局,item(类似UITableView中的cell)会排列在上一个item的右边,如果屏幕空间不够,它会自动排到下一行,和水流一样。

代码如下:

  • (UICollectionView *)collectionView
    {
    if (!_collectionView) {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.currentLayout = layout;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 240) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[ZQCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    }

    return _collectionView;
    }

我们现在想实现一个这样的效果:
当左右拖动item的时候,靠近屏幕中心item放大,远离中心的item缩小
左右滑动的时候,停止下来的item的中心永远和屏幕中心对齐

效果如图:
linear

首先,我们需要自定义UICollectionViewLayout。由于需求效果仍然保持流水特性,我们选择继承UICollectionViewFlowLayout。需要重写的方法如下:

  • (void)prepareLayout:该方法是每次布局时一些准备工作,可以在这里做一些初始化的操作,记得调用super实现!
  • (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds:当布局的边界发送改变的时候,会询问该方法是否重新布局
  • (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:返回可见的rect中所有的Elements的布局属性(UICollectionViewLayoutAttributes)。在UICollectionViewLayoutAttributes可设置item的size、center、transform等等属性,来精确定制item的位置和形变.UICollectionViewFlowLayout对该方法有一个默认实现,可使item流水式排列。而UICollectionViewLayout则完全是空实现,需要我们自己计算
  • (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity:当item被滑动自行停止时,我们可以根据这个方法设定item停在我们期望的地方

代码如下:

  • (void)prepareLayout
    {
    [super prepareLayout];
    // 每个item的size
    self.itemSize = CGSizeMake(ITEM_SIZE, ITEM_SIZE);
    // 最小间距
    self.minimumLineSpacing = 50;
    // 横向滚动
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 内间距
    self.sectionInset = UIEdgeInsetsMake(90, (self.collectionView.bounds.size.width - ITEM_SIZE) * 0.5, 40, 150);
    }

  • (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
    return YES;
    }

  • (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
    {
    // 当前屏幕的rect
    CGRect visiableRect = {proposedContentOffset, self.collectionView.bounds.size};
    CGFloat currentCenterX = proposedContentOffset.x + self.collectionView.bounds.size.width * 0.5;
    // 调用super实现可以获取到当前rect中所有item的布局属性
    NSArray *attributesArray = [super layoutAttributesForElementsInRect:visiableRect];
    CGFloat adjustDistance = MAXFLOAT;
    // 计算距离中心点最近的item,来算偏移量
    for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
    if (CGRectIntersectsRect(attributes.frame, visiableRect)) {// 在屏幕内
    CGFloat x = attributes.center.x;
    if (ABS(x - currentCenterX) < ABS(adjustDistance)) {
    adjustDistance = x - currentCenterX;
    }
    }
    }

    return CGPointMake(proposedContentOffset.x + adjustDistance, proposedContentOffset.y);
    }

  • (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
    CGRect visiableRect = {self.collectionView.contentOffset, self.collectionView.bounds.size};
    CGFloat currentCenterX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width * 0.5;
    NSArray *attributesArray = [super layoutAttributesForElementsInRect:visiableRect];
    for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
    if (CGRectIntersectsRect(attributes.frame, visiableRect)) {// 在屏幕内
    CGFloat itemCenterX = attributes.center.x;
    // 设定一个放大的系数,公式大家可以自己来定,效果接近就可以
    CGFloat scale = 1 + SCALE_FACTOR * (1 - (ABS(itemCenterX - currentCenterX) / SCALE_BIG_DISTANCE));
    attributes.transform3D = CATransform3DMakeScale(scale, scale, 1.0);
    }
    }
    return attributesArray;
    }

以上是继承UICollectionViewFlowLayout的布局,如果我们想做一次更深层次的定制,我们可以直接继承UICollectionViewLayout来完全自定义布局,要重写的方法和UICollectionViewFlowLayout类似,只是我们需要自己来实现这些方法:

  • (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:需要自己新建UICollectionViewLayoutAttributes,也可以通过下面的方法2完成
  • (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath:该方法确定当前indexPath下的item的布局属性

代码如下:

  • (void)prepareLayout
    {
    [super prepareLayout];
    }

  • (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
    return YES;
    }

  • (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    NSMutableArray *attributesArray = [NSMutableArray array];
    for (NSInteger i = 0; i < count; ++i) {
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    [attributesArray addObject:attributes];
    }
    return attributesArray;
    }

  • (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    CGPoint currentCenter = CGPointMake(self.collectionView.contentOffset.x + self.collectionView.bounds.size.width * 0.5, self.collectionView.bounds.size.height * 0.5);
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attributes.size = CGSizeMake(ITEM_SIZE, ITEM_SIZE);

    CGFloat angelDelta = M_PI * 2 / count;
    CGFloat angel = M_PI_2 - angelDelta * indexPath.row;
    attributes.center = CGPointMake(currentCenter.x + CIRCLE_RADIUS * cosf(angel), currentCenter.y + CIRCLE_RADIUS * sinf(angel));
    return attributes;

}
以上可实现一个环形(circle)布局, demo中还添加了点击item就把该item删除的事件
circel

还可以做一个类似蜂巢的布局:

  • (CGSize)collectionViewContentSize
    {
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    return CGSizeMake(0, (count / COL)* count);
    }

  • (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

    UICollectionView *collection = self.collectionView;

    float x = (SIZE + self.margin) * (indexPath.item % COL + 1) * 0.75 + 40;
    float y = (SIZE + self.margin) * (indexPath.item / COL + 0.5) * cos(M_PI * 30.0f / 180.0f) + 20;
    if (indexPath.item % 2 == 1) {
    y += (SIZE + self.margin) * 0.5 * cosf(M_PI * 30.0f / 180.0f);
    }

    attributes.center = CGPointMake(x + collection.contentOffset.x, y + collection.contentOffset.y);
    attributes.size = CGSizeMake(SIZE, SIZE * cos(M_PI * 30.0f / 180.0f));

    return attributes;
    }

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *arr = [super layoutAttributesForElementsInRect:rect];
if ([arr count] > 0) {
return arr;
}
NSMutableArray *attributes = [NSMutableArray array];
for (NSInteger i = 0 ; i < [self.collectionView numberOfItemsInSection:0 ]; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
}
return attributes;
}

其中cell的样式:

  • (instancetype)initWithFrame:(CGRect)frame

{

if (self = [super initWithFrame:frame]) {

    self.backgroundColor = ZQRandomColor;

    CGFloat longSide = SIZE * 0.5 * cosf(M_PI * 30 / 180);

    CGFloat shortSide = SIZE * 0.5 * sinf(M_PI * 30 / 180);

    UIBezierPath *path = [UIBezierPath bezierPath];

    [path moveToPoint:CGPointMake(0, longSide)];

    [path addLineToPoint:CGPointMake(shortSide, 0)];

    [path addLineToPoint:CGPointMake(shortSide + SIZE * 0.5, 0)];

    [path addLineToPoint:CGPointMake(SIZE, longSide)];

    [path addLineToPoint:CGPointMake(shortSide + SIZE * 0.5, longSide * 2)];

    [path addLineToPoint:CGPointMake(shortSide, longSide * 2)];

    [path closePath];

    

    CAShapeLayer *maskLayer = [CAShapeLayer layer];

    maskLayer.path = [path CGPath];

    

    self.layer.mask = maskLayer;

}

return self;

}

效果如图:
honeycomb

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容