iOS UICollectionView的使用(用storyboard和xib建立)

1. 在storyboard中,拖出1個UICollectionViewControlleride

2. 新建file--Cocoa Touch Class,繼承自UICollectionViewController,假設名字是CollectionDemo佈局

3. 在storyboard, 把剛纔拖出來的UICollectionViewController的class改爲CollectionDemoatom

4. 在 CollectionDemo.m 中實現,數據源方法spa

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)sectionblog

{繼承

    return self.photos.count;圖片

}element

 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPathit

{io

    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

相關文章
相關標籤/搜索