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

iOS:UICollectionView 的子類化封裝

編輯:iOS 開發綜合

UICollectionView 的建立方式與 UITableView 大同小異,但把常見設定收攏到子類別中,能讓使用端清爽不少。本文示範如何建立一個自訂的 collectionView 子類,並說明 cell、頭視圖與 flowLayout 的處理。

一、建立子類別並在初始化中設定屬性

- (id)initWithFrame:(CGRect)frame {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;  // 列間距
    flowLayout.minimumLineSpacing = 0;       // 行間距

    self = [super initWithFrame:frame collectionViewLayout:flowLayout];
    if (self) {
        // 隱藏滾動條
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;

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

        // 設定背景顏色(預設為黑色)
        self.backgroundColor = [UIColor whiteColor];

        // 註冊單元格
        [self registerClass:[YSStudentStatusCell class] forCellWithReuseIdentifier:identify];
    }
    return self;
}

二、cell 的建立

collectionView 的協議方法與 tableView 幾乎一致,主要差別在於 cell 與頭視圖的建立方式。

// 建立 cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                    cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ModelStudent *model = self.dataArray[indexPath.item];

    // 子類化的 cell
    YSStudentStatusCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify
                                                                          forIndexPath:indexPath];
    [cell configureWithModel:model.StuUserInfo];
    return cell;
}

子類化 cell 的初始化方法如下,這裡用 init 不會被呼叫,所以要寫在 initWithFrame: 中:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}

三、頭視圖的註冊與建立

使用 supplementary view 之前必須先註冊,這一步通常和 cell 註冊寫在同一處:

// collection 頭視圖的註冊
[self registerClass:[UICollectionReusableView class]
    forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
           withReuseIdentifier:@"Identifierhead"];

建立頭視圖的協議方法:

// 組的頭視圖建立
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
          viewForSupplementaryElementOfKind:(NSString *)kind
                                atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *headView =
        [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                           withReuseIdentifier:@"Identifierhead"
                                                  forIndexPath:indexPath];
    headView.backgroundColor = [UIColor blueColor];
    return headView;
}

四、關於 flowLayout

flowLayout 可以說是 collectionView 的布局靈魂:替換不同的 layout 物件,就能載入完全不同的排列樣式,從簡單的網格到瀑布流、輪播卡片都難不倒它。

實務上還有一個細節:UICollectionViewCell 不像 UITableViewCell 那樣預設自帶 contentView 排版結構,所有子視圖都要自己建立並加上約束;另外它沒有內建的左滑操作與分隔線,這些都需要自行實作。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved