美文网首页
UICollectionView基本框架

UICollectionView基本框架

作者: 杨大虾 | 来源:发表于2017-07-06 14:36 被阅读23次

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;
}

相关文章

网友评论

      本文标题:UICollectionView基本框架

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