UICollection要点

一、UICollectionView 要点

  • UICollectionLayout布局方法的执行顺序
  • UICollectionLayout实现自定义布局要点
  • UICollectionViewLayoutAttributes实现自定义布局属性要点
  • 重新计算布局属性
  • 自动对齐到网格

1、UICollectionView 构成

  • Cells
  • Supplementary Views 追加视图(类似Header 或则 Footer)
  • Decoration Views 装饰视图(用作背景展示)

2、布局方法的执行顺序

  1. prepareLayout()
  2. -(CGSize)collectionViewContentSize
  3. -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

3、自定义UICollectionLayout实现自定义布局

主要继承UICollectionLayout以下方法,实现布局自定义。

  • -(void)prepareLayout

    开始布局前,调用的方法。可以用来一次把所有的布局属性放到一个NSArray中。

  • -(CGSize)collectionViewContentSize

    返回CollectionView的内容尺寸

  • -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

    1. 返回rect中的所有元素的布局属性
    2. 返回的是包含UICollectionViewLayoutAttributes的NSArray
    3. UICollectionViewLayoutAttributes可以是Cell追加视图装饰视图
    4. 不要返回所有的属性,只显示Rect相交的属性。节省性能。
  • -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

    YES : 边界发生变化,刷新布局。
    不要直接返回YES,判断UICollectionView的frame改变时再返回YES。

  • -(UICollectionViewLayoutAttributes _)layoutAttributesForItemAtIndexPath:(NSIndexPath _)indexPath

    返回对应于indexPath的位置的Cell的布局属性

  • -(UICollectionViewLayoutAttributes _)layoutAttributesForSupplementaryViewOfKind:(NSString _)kind atIndexPath:(NSIndexPath *)indexPath

    返回对应于indexPath的位置的追加视图的布局属性

  • -(UICollectionViewLayoutAttributes * )layoutAttributesForDecorationViewOfKind:(NSString_)decorationViewKind atIndexPath:(NSIndexPath _)indexPath

    返回对应于indexPath的位置的装饰视图的布局属性

4、自定义UICollectionViewLayoutAttributes

主要用来布局cell、追加视图、装饰视图里面的指定子元素。

  • 实现NSCopying协议?
  • 实现-(BOOL)isEqual:(id)object父类方法?
  • 在cell、追加视图、装饰视图中,实现-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes方法,具体布局指定元素。
  • 在Layout类中实现以下方法?
    • +(Class)layoutAttributesClass

5、重新计算布局

  • invalidateLayout:执行布局方法,从-(void)prepareLayout方法开始重新计算布局。

6、切换布局

注意:切换的2个布局必须已经实现了 -(UICollectionViewLayoutAttributes _)layoutAttributesForItemAtIndexPath:(NSIndexPath _)indexPath方法。否则会报错。

  • setCollectionViewLayout:animated:

7、动画效果

  • initialLayoutAttributesForAppearingItemAtIndexPath:
  • initialLayoutAttributesForAppearingSupplementaryElementOfKind:atIndexPath:
  • initialLayoutAttributesForAppearingDecorationElementOfKind:atIndexPath:
  • finalLayoutAttributesForDisappearingItemAtIndexPath:
  • finalLayoutAttributesForDisappearingSupplementaryElementOfKind:atIndexPath:
  • finalLayoutAttributesForDisappearingDecorationElementOfKind:atIndexPath:

8、DEMO与参考

转载于:https://my.oschina.net/u/2385300/blog/826220

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值