美文网首页
UICollectionView

UICollectionView

作者: Shorebloom_59f6 | 来源:发表于2018-11-16 19:01 被阅读0次

一、使用

  1. 使用collectionView 时首先要创建一个布局以供collectionView使用。一般使用UICollectionViewFlowLayout。也可使用自定义的布局。
  2. 创建collectionView 设置数据源及代理(未使用到代理方法可不设置)
  3. 注册collectionView 所使用的cell 分两种
// 注册cell类(自定义或UICollectionViewCell)
- (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
// 从Xib注册
- (void)registerNib:(nullable UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
  1. 注册头视图、尾视图(无需要可不注册)
    kind = UICollectionElementKindSectionHeader 头部
    kind = UICollectionElementKindSectionFooter 尾部
- (void)registerClass:(nullable Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(nullable UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;

  1. 实现数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

二、collectionView 自定义布局

  1. 自定义布局需要实现的几个方法
/** 准备布局 */
- (void)prepareLayout;

/** 返回rect范围内的item的布局数组(这个方法会频繁调用) */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;

/** 返回indexPath位置的item布局属性  */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

/** 返回collectionView的contentSize  */
- (CGSize)collectionViewContentSize;
  1. 常见的布局:瀑布流布局、卡片式布局等

相关文章

网友评论

      本文标题:UICollectionView

      本文链接:https://www.haomeiwen.com/subject/ihqvfqtx.html