在控制器中添加CollectionView
在控制器的viewDidLoad方法中初始化CollectionView
static NSString *ID = @"collectionViewCell";
- (void)viewDidLoad {
[super viewDidLoad];
// UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds]; 这种初始化方法,无法编译通过
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]]; // 这里不要用UICollectionViewLayout,UICollectionViewLayout是抽象基类,是专门用于子类继承的; UICollectionViewFlowLayout是最基本的布局
collectionView.dataSource = self;
collectionView.delegate = self;
[self.view addSubview:collectionView];
// 一般都会自定义一个CollectionViewCell,因为系统预制的CollectionViewCell,不像tableViewCell那样有Label,ImageView,CollectionViewCell只有2个View:backgroundView和selectedBackgroundView
[collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:ID];
}
#pragma mark - collectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1; // 和tableView一样
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.photos.count; // 和tableView一样
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
// 不需要再写 if (!cell) { 初始化cell; }
// indexPath.row 也行,可能collectionView布局更自由,不像tableView那样一般都是“行”,所以更多人喜欢用indexPath.item吧
[cell.imageV setImage:[UIImage imageNamed:self.photos[indexPath.item]]];
return cell;
}
自定义CollectionViewCell
// CustomCell.h
@interface CustomCell : UICollectionViewCell
@property (nonatomic, weak) UIImageView *imageV;
@end
// CustomCell.m
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIImageView *imageView = [[UIImageView alloc]init];
imageView.frame = CGRectMake(5, 5, 40, 40);
[self addSubview:imageView];
_imageV = imageView;
}
return self;
}