您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用一行程式碼搞定 UITableView 的 Delegate 與 DataSource:CBTableViewDataSource 介紹

編輯:iOS 技巧大全

只要一行程式碼,就能替 UITableView 建立好 DataSource 與 Delegate,這聽起來有點誇張,但 CBTableViewDataSource 確實做到了。

[_tableView cb_makeSectionWithData:self.viewModel.data
                        andCellClass:[CustomCell class]];

一、傳統寫法有多繁瑣

一般專案裡,多 section 的表單式畫面往往要寫成這樣:

// 用列舉切分 section
typedef NS_ENUM(NSInteger, SectionNameDefine) {
    SECTION_ONE,
    SECTION_TWO,
    SECTION_THREE,
    SECTION_FOUR,
    COUNT_OF_STORE_SECTION
};

// 為每個 section 定義 reuse identifier
#define IDENTIFIER_ONE   @"IDENTIFIER_ONE"
#define IDENTIFIER_TWO   @"IDENTIFIER_TWO"
#define IDENTIFIER_THREE @"IDENTIFIER_THREE"
#define IDENTIFIER_FOUR  @"IDENTIFIER_FOUR"

// 逐一註冊 cell
[self.tableView registerClass:[OneCell class]   forCellWithReuseIdentifier:IDENTIFIER_ONE];
[self.tableView registerClass:[TwoCell class]   forCellWithReuseIdentifier:IDENTIFIER_TWO];
[self.tableView registerClass:[ThreeCell class] forCellWithReuseIdentifier:IDENTIFIER_THREE];
[self.tableView registerClass:[FourCell class]  forCellWithReuseIdentifier:IDENTIFIER_FOUR];

// 再實作三個 delegate 方法,並用 switch 判斷 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return COUNT_OF_STORE_SECTION;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return ((NSArray *)self.data[section]).count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case SECTION_ONE:   /* ... */ return cell;
        case SECTION_TWO:   /* ... */ return cell;
        case SECTION_THREE: /* ... */ return cell;
    }
    return cell;
}

步驟多、樣板程式碼長,section 一多維護起來非常痛苦。

二、改用宣告式的寫法

[_tableView cb_makeDataSource:^(CBTableViewDataSourceMaker *make) {

    [make makeSection:^(CBTableViewSectionMaker *section) {
        section.cell([OneCell class])
               .data(self.viewModel.oneData)
               .adapter(^(OneCell *cell, id data, NSUInteger index) {
                    [cell configure:data];
               })
               .autoHeight();
    }];

    [make makeSection:^(CBTableViewSectionMaker *section) {
        section.cell([TwoCell class])
               .data(self.viewModel.twoData)
               .adapter(^(TwoCell *cell, id data, NSUInteger index) {
                    [cell configure:data];
               })
               .autoHeight();
    }];

    // ... 其餘 section 同理
}];

程式碼變得精簡而有層次,也更貼近人思考的方式:一個 section 一段描述,各管各的資料與樣板。

三、安裝與基本用法

透過 CocoaPods 安裝:

pod 'CBTableViewDataSource'

引入標頭:

#import <CBTableViewDataSource/CBTableViewDataSource.h>

四、只用資料,不寫自訂 Cell

_data = @[
    @{@"text": @"Following", @"value": @"45"},
    @{@"text": @"Follower",  @"value": @"10"},
    @{@"text": @"Star",      @"value": @"234"},
    @{@"text": @"Setting",   @"accessoryType": @(UITableViewCellAccessoryDisclosureIndicator)},
    @{@"text": @"Share",     @"accessoryType": @(UITableViewCellAccessoryDisclosureIndicator)}
];

更完整的用法可參考專案中的 DemoTwoViewController。

五、自訂 Cell 的資料綁定

- (void)configure:(NSDictionary *)row index:(NSNumber *)index {
    if (row[@"avatar"]) {
        self.avatarView.image = [UIImage imageNamed:row[@"avatar"]];
    } else {
        self.avatarView.image = nil;
    }
    self.nameLabel.text   = row[@"name"];
    self.titleLabel.text  = row[@"title"];
    self.detailLabel.text = row[@"detail"];

    // 隔行變色
    if ([index intValue] & 1) {
        self.contentView.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.0];
    } else {
        self.contentView.backgroundColor = [UIColor whiteColor];
    }
}

六、更靈活的單一 section 設定

[tableView cb_makeSection:^(CBTableViewSectionMaker *section) {
    section.data(@[]);
    section.cell([CustomCell class]);
    section.adapter(^(CustomCell *cell, id row, NSUInteger index) {
        cell.configure(row);
    });
    section.event(^{ /* 點擊後要做的事 */ });
    // 其他設定
}];

CBTableViewSectionMaker 支援的屬性(皆為單一 section 等級):

data:傳入 NSArray,作為該 section 的資料來源。

cell:指定 cell 類別,框架會自動註冊 identifier,不需手動 register。

adapter:把 cell 與 data 綁在一起,在這裡呼叫 cell 的設定方法。

event:點擊 cell 的回呼,通常寫跳轉邏輯。

height:固定高度,僅對該 section 有效。

autoHeight:自動計算高度,適合高度不齊的情境。與 height 衝突時,autoHeight 優先。

headerTitle/footerTitle:設定 section 的標題文字。

headerView/footerView:自訂 section 的頭尾視圖,與 title 並存時以 view 為準。

七、多 section 的整體設定

[tableView cb_makeDataSource:^(CBTableViewDataSourceMaker *make) {

    [make headerView:^{ return [HeaderView new]; }];

    [make makeSection:^(CBTableViewSectionMaker *section) {
        section.data(@[]);
        section.cell();
        section.adapter();
        section.event();
    }];

    [make makeSection:^(CBTableViewSectionMaker *section) { /* ... */ }];

    [make footerView:^{ return [FooterView new]; }];
}];

CBTableViewDataSourceMaker 支援的屬性(針對整個 UITableView):

makeSection:新增一個 section。

height:全表預設高度。優先級為 autoHeight > section 的 height > tableview 的 height,兩者皆未設定時預設 40。

headerView/footerView:對應 tableHeaderView 與 tableFooterView,整張表只有一個。

commitEditing:對應 commitEditingStyle 代理,設定後 cell 側滑會出現刪除鈕。

scrollViewDidScroll:對應滾動回呼,可用來處理捲動時的行為。

八、致謝

這個框架的 API 設計參考了 Masonry 的宣告式風格,而動態計算 cell 高度的部分則參考了 @forkingdog 的 UITableView-FDTemplateLayoutCell。感謝這些專案帶來的靈感。

專案下載:
https://www.code4app.com/thread-8859-1-1.html

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