您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UICollectionView 純程式碼實作(不使用 xib)

編輯:iOS 開發綜合

UICollectionView 是 iOS 上最靈活的列表元件,但很多人第一次寫會卡在「Cell 一定要註冊」這一步。這篇用純程式碼把整個流程跑一遍,不依賴 storyboard 或 xib。

為什麼一定要註冊 Cell

和 UITableView 不同,UICollectionView 在 dequeueReusableCellWithReuseIdentifier:forIndexPath: 時,若找不到對應的註冊或 xib,會直接拋出例外,不會像舊寫法那樣回傳 nil 讓你自己 new。可用的註冊方法有四個:

- (void)registerClass:forCellWithReuseIdentifier:
- (void)registerClass:forSupplementaryViewOfKind:withReuseIdentifier:
- (void)registerNib:forCellWithReuseIdentifier:
- (void)registerNib:forSupplementaryViewOfKind:withReuseIdentifier:

純程式碼專案使用第一個即可。

建立 CollectionView

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1. 建立並設定流水式版面
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    // 2. 用版面物件初始化
    self.collectionView = [[UICollectionView alloc]
        initWithFrame:CGRectMake(0, kNavHeight, kDeviceWidth,
                                 kDeviceHeight - kNavHeight * 2 - kTabBarHeight - 20)
        collectionViewLayout:flowLayout];

    // 3. 註冊 Cell(關鍵步驟)
    [self.collectionView registerClass:[VideoCell class]
          forCellWithReuseIdentifier:@"cell"];

    // 4. 設定代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

    [self.view addSubview:self.collectionView];
}

資料源方法

#pragma mark - UICollectionViewDataSource

// 分區數量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

// 每個分區的項目數
- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return 24;
}

// 設定每個 cell 的內容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identify = @"cell";
    VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify
                                                              forIndexPath:indexPath];

    VideoModel *model = self.videoModels[indexPath.row];
    [cell.imgView setImageWithURL:[NSURL URLWithString:model.videoImgURL]];
    cell.titleLabel.text = model.videoTitle;

    return cell;
}

這裡有個常見誤解:因為 dequeue 保證會回傳一個實例(必要時才建立),所以 if (!cell) 這種判斷式在註冊過的情況下永遠不會成立,可以移除。

版面配置:由 Flow Layout 的代理決定

間距、尺寸、頁首大小都不是在 dataSource 設定,而是在 UICollectionViewDelegateFlowLayout 中:

#pragma mark - UICollectionViewDelegateFlowLayout

// 四周內縮
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 10, 15, 5);  // 上、左、下、右
}

// 每個項目的大小
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = (kDeviceHeight - kNavHeight * 2 - kTabBarHeight - 20) / 4.0;
    return CGSizeMake(240, height);
}

// 頁首大小,不需要時回傳 CGSizeZero
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 0);
}

點擊事件

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    DetailVideoViewController *detailVC = [[DetailVideoViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

實務小結

  • 記得在 UICollectionViewDelegateFlowLayout 之外,也要宣告遵循 UICollectionViewDelegate 與 UICollectionViewDataSource。
  • 想要多欄並排,只需調整 sizeForItemAtIndexPath: 的寬度與 insetForSectionAtIndex: 的間距,不必改動其他程式碼。
  • 若版面需求超出 Flow Layout 的能力(例如瀑布流、圓形排列),就自訂一個繼承 UICollectionViewLayout 的類別,覆寫 layoutAttributesForElementsInRect:。
  • Cell 內的圖片載入建議加上快取與取消機制,快速捲動時才不會出現圖片錯位。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved