UICollectionView基本框架

1.collectionView


static NSString *identifier = @"CollectionCell";

- (UICollectionView *)collectionView
{
    __weak typeof(self)weakSelf = self;
    if (!_collectionView) {
        /*最最原始的流水布局
    这里可以替换自己自定义的布局
           */
   UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
         //_layout = layout;
   layout.itemSize = CGSizeMake(100, 100);
        // 创建collectionView
   _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,weakSelf.view.frame.size.width , weakSelf.view.frame.size.height - 64) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = weakSelf;
        _collectionView.dataSource = weakSelf;
        //注册
        [_collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:identifier];
    }
    return _collectionView;
}

1.1dataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageNames.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    NSString *a = self.imageNames[indexPath.item];
    cell.imageView.image = [UIImage imageNamed:a];
    return cell;
}

1.2delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.imageNames removeObjectAtIndex:indexPath.item];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

2.item(有注册的写法相对简便一点)

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
                
        CGFloat imageW = self.contentView.frame.size.width;
        CGFloat imageH = self.contentView.frame.size.height;
        UIImageView *image = [[UIImageView alloc] init];
        image.frame = CGRectMake(0, 0, imageW, imageH);

        [self.contentView addSubview: image];
        
        _imageView = image;        
    }
    return self;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容