標籤:
1. 在storyboard中,拖出1個UICollectionViewController
2. 建立file--Cocoa Touch Class,繼承自UICollectionViewController,假設名字是CollectionDemo
3. 在storyboard, 把剛才拖出來的UICollectionViewController的class改成CollectionDemo
4. 在 CollectionDemo.m 中實現,資料來源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.photos.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"cell";
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.imageView.image = [UIImage imageNamed:self.photos[indexPath.item]];
return cell;
}
5. 修改storyboard的CollectionViewCell,比如修改背景色,放一張圖片,設定圖片的約束,最重要的是修改重用標記為cell,也就是要和代碼裡寫的相一致
6. 建立自訂collectionViewCell類,添加輸出口,也就是和storyboard的控制項做連線
@interface CustomCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
7. 運行效果
8. 和純程式碼建立CollectionView相比,省了如下步驟
[collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:ID]; // 註冊cell
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]]; // 初始化的時候,指定布局
// 還有自訂cell的構造方法
- (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;
}
註:storyboard拖出來的collectionViewController預設就是流水布局
四種註冊方法的異同
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;
cell是代碼建立的用第1種;
如果cell是xib建立的,用第2種;
下面2個是用於註冊補充視圖,補充視圖類似於tableView的 SectionHeader,SectionFooter,它通過elementKind參數區別補充視圖頭還是補充視圖尾,尾UICollectionElementKindSectionFooter 頭UICollectionElementKindSectionHeader
iOS UICollectionView的使用(用storyboard和xib建立)