[个人博客搬运]定制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;
}

 


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

效果如图:
linear

首先,我们需要自定义UICollectionViewLayout。由于需求效果仍然保持流水特性,我们选择继承UICollectionViewFlowLayout。需要重写的方法如下:
  1. - (void)prepareLayout:该方法是每次布局时一些准备工作,可以在这里做一些初始化的操作,记得调用super实现!

  2. - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds:当布局的边界发送改变的时候,会询问该方法是否重新布局

  3. - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:返回可见的rect中所有的Elements的布局属性(UICollectionViewLayoutAttributes)。在UICollectionViewLayoutAttributes可设置item的size、center、transform等等属性,来精确定制item的位置和形变.UICollectionViewFlowLayout对该方法有一个默认实现,可使item流水式排列。而UICollectionViewLayout则完全是空实现,需要我们自己计算

  4. - (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类似,只是我们需要自己来实现这些方法:

  1. - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:需要自己新建UICollectionViewLayoutAttributes,也可以通过下面的方法2完成
  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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值