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);
// 創(chuàng)建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(有注冊的寫法相對簡便一點(diǎn))
- (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;
}