继承UICollectionViewFlowLayout的自定义布局

重写prepareLayout方法

  • 作用: 在这个方法中做一些初始化操作
  • 注意: 一定要调用[super prepareLayout]

重写layoutAttributesForElementsInRect:方法

  • 作用:

    • 这个方法的返回值是个数组
    • 这个数组中存放的都是UICollectionViewLayoutAttributes对象
    • UICollectionViewLayoutAttributes对象决定了cell的排布方式(frame等)
  • 解决bug
    Logging only once for UICollectionViewFlowLayout cache mismatched frame
    UICollectionViewFlowLayout has cached frame mismatch for index path <NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1} - cached value: {{304.5, 57.000000000000007}, {86, 86}}; expected value: {{272.5, 25}, {150, 150}}
    This is likely occurring because the flow layout subclass WLWLineLayout is modifying attributes returned by UICollectionViewFlowLayout without copying them
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    改为
    NSArray *original = [super layoutAttributesForElementsInRect:rect];
    NSArray *array = [[NSArray alloc] initWithArray:original copyItems:YES];

重写shouldInvalidateLayoutForBoundsChange:方法

  • 作用: 如果返回YES,那么collectionView显示的范围发生改变时,就会从新刷新布局
  • 一旦从新刷新布局,就会顺序调用下面的方法
    • prepareLayout
    • layoutAttributesForElementsInRect:

重写targetContentOffsetForProposedContentOffset: withScrollingVelocity:方法

  • 作用: 返回值决定了collectionView停止滚动时最终的偏移量 (contentOffset)
  • 参数:
    • proposedContentOffset: 原本情况下,collectionView停止滚动时的偏移量
  • velocity: 滚动速率,通过这个参数可以了解滚动的方向
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容