美文网首页iOS 较好的文章
UICollectionView 基本使用

UICollectionView 基本使用

作者: mayday2024 | 来源:发表于2015-05-18 22:18 被阅读3799次

控制器继承UICollectionViewController 它自动遵守数据源 和 代理了。

1.实现数据源方法

pragma mark - collectionView数据源方法

/**

  • 有多少组
    */
  • (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
    }

/**

  • 第section有多少个格子
    */
  • (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.products.count;
    }

/**

  • 返回怎样cell
    */
  • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 0.声明重用标示
    static NSString *ID = @"Product";
    // 1.创建cell
    CZProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    // cell.backgroundColor = [UIColor orangeColor];

    // 2.获得indexPath.item对应product模型
    CZProduct *product = self.products[indexPath.item];
    cell.product = product;

    return cell;

}

2。注册cell (viewDidLoad 方法实现)
(这个cell 是XIB) XIB 里面要设置 彩票那
// 注册cell(如果缓存池没有找到对应cell,则会创建该方法注册的cell)
UINib *nib = [UINib nibWithNibName:@"CZProductCell" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:@"Product"];

3.布局

  • (instancetype)init {

// UICollectionViewLayout *layout = [[UICollectionViewLayout alloc] init];要子类才行 下面这个
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
// 设置item尺寸
layout.itemSize = CGSizeMake(80, 80);
// 设置item之间的间隔
layout.minimumInteritemSpacing = 0;
// 设置行之间间隔
layout.minimumLineSpacing = 20;
// 设置组的内边距
layout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
if (self = [super initWithCollectionViewLayout:layout]) {

}
return self;

}

另外这种自定义CELL是没有XIB的
// 注册cell,默认就会创建这个类型的cell
[self.collectionView registerClass:[CZNewFeatureCell class] forCellWithReuseIdentifier:ID];

// 分页(这个是新特性那里)
self.collectionView.pagingEnabled = YES;
self.collectionView.bounces = NO;
self.collectionView.showsHorizontalScrollIndicator = NO;

//也是重写init

  • (instancetype)init
    {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    // 设置cell的尺寸
    layout.itemSize = [UIScreen mainScreen].bounds.size;
    // 清空行距
    layout.minimumLineSpacing = 0;

    // 设置滚动的方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    return [super initWithCollectionViewLayout:layout];
    }

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}

相关文章

网友评论

    本文标题:UICollectionView 基本使用

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