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


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM