整理 Table View 的代碼

轉自:http://tang3w.com/translate/objective-c/objc.io/2013/10/23/整理-table-view-的代碼.html


注:這篇翻譯已經過 objc.io 授權,原文鏈接是:Clean table view code

Table view 是 iOS 應用程序中非常通用的組件。所以許多代碼和 table view 都有直接或間接的關係,包括提供數據、更新 table view,控制它的行爲以及響應選擇事件,僅舉這幾個例子。在這篇文章中,我們將會展示保持代碼整潔和組織良好的技術。

UITableViewController vs. UIViewController

Apple 提供了 UITableViewController 作爲 table views 專屬的 view controller 類。Table view controllers 實現了一些非常有用的特性來幫你避免一遍又一遍地寫那些死板的代碼!但是話又說回來,table view controller 只限於管理一個全屏展示的 table view。大多數情況下,這就是你想要的,但如果不是,還有其他方法來解決這個問題,就像下面我們展示的那樣。

Table View Controllers 的特性

Table view controllers 會在第一次顯示 table view 的時候幫你加載其數據。特別地,他還會幫你切換 table view 的編輯模式、響應鍵盤通知、以及一些小任務,比如閃現 scroll indicator 和消除選擇。爲了讓這些特性生效,當你在子類中覆寫事件方法時,需要調用 super。

Table view controllers 相對於標準 view controllers 的唯一賣點就是它支持 Apple 實現的“下拉刷新”。目前,整個文檔只有在 table view controller 中使用過 UIRefreshControl,雖然在其他幾種上下文中也能工作(見此處),但很可能在下一次 iOS 更新的時候無法工作。

這些元素提供了 Apple 爲 table view 定義的大多數交互行爲,如果你的應用恰好符合這些特性,那麼堅持使用 table view controllers 來避免寫那些死板的代碼是個很好的方法。

Table View Controllers 的限制

Table view controllers 的 view 屬性永遠都是一個 table view。如果你稍後決定在 table view 旁邊顯示一些東西(比如一個地圖),如果不依賴於那些奇怪的 hacks,你就不會那麼走運了。

如果你用代碼或 .xib 文件定義了界面,那麼遷移到一個標準 view controller 將會非常簡單。如果你使用了 storyboards,那麼這個過程要多包含幾個步驟。你不能在 storyboards 中將 table view controller 改成一個標準的 view controller,除非你重新創建它。這意味着你必須將所有內容拷貝到新的 view controller,然後再重新連接一遍。

最後,你需要把遷移後丟失的 table view controller 的特性給補回來。大多數都是viewWillAppear 或 viewDidAppear 中簡單的一條語句。切換編輯模式需要實現一個 action 方法,用來切換 table view 的 editing 屬性。大多數工作來自對鍵盤的支持。

在選擇條路之前,你還有一個更輕鬆的選擇,它有分離關注點 ( separating concerns ) 的額外好處:

Child View Controllers

和完全拋棄 table view controller 不同,你還可以將它作爲 child view controller 添加到其他 view controller 中(看關於此問題的文章)。然後 table view controller 繼續管理它的 table view,如果需要,parent view controller 可以關心其他的界面元素。

- (void)addPhotoDetailsTableView
{
    DetailsViewController *details = [[DetailsViewController alloc] init];
    details.photo = self.photo;
    details.delegate = self;
    [self addChildViewController:details];
    CGRect frame = self.view.bounds;
    frame.origin.y = 110;
    details.view.frame = frame;
    [self.view addSubview:details.view];
    [details didMoveToParentViewController:self];
}

如果你使用這個解決方案,你就必須在 child view controller 和 parent view controller 之間建立消息傳遞的渠道。比如,如果用戶選擇了一個 table view 中的 cell,parent view controller 需要知道這個事件來推入其他 view controller。根據使用習慣,通常最清晰的方式是爲這個 table view controller 定義一個 delegate protocol,然後到 parent view controller 中去實現。

@protocol DetailsViewControllerDelegate
- (void)didSelectPhotoAttributeWithKey:(NSString *)key;
@end

@interface PhotoViewController () <DetailsViewControllerDelegate>
@end

@implementation PhotoViewController
// ...
- (void)didSelectPhotoAttributeWithKey:(NSString *)key
{
    DetailViewController *controller = [[DetailViewController alloc] init];
    controller.key = key;
    [self.navigationController pushViewController:controller animated:YES];
}
@end

就像你看到的那樣,這種結構爲 view controller 之間的消息傳遞帶來了額外的開銷,但是作爲回報,獲得了清晰的關注點分離和更好的可複用性。根據實際情況來看,這既沒有讓事情變得更簡單,也沒有更復雜,請讀者自行斟酌。

分離關注點(Separating Concerns)

當處理 table views 的時候,有許多各種各樣的任務,這些任務穿梭於 models,controllers 和 views 之間。爲了避免讓 view controllers 做所有的事,我們將儘可能地把這些任務劃分到合適的地方,這樣有利於閱讀、維護和測試。

這裏描述的技術是文章更輕量的 View Controllers 中的概念的延伸,請參考這篇文章來理解如何重構 data source 和 model 的邏輯。結合 table views,我們來具體看看如何在 view controllers 和 views 之間分離關注點。

搭建 Model 對象和 Cells 之間的橋樑

有時我們需要處理在 view layer 中顯示的數據。由於我們同時也希望讓 model 和 view 之間明確分離,所以通常把這個任務轉移到 table view 的 data source 中去做。

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PhotoCell"];
    Photo *photo = [self itemAtIndexPath:indexPath];
    cell.photoTitleLabel.text = photo.name;
    NSString* date = [self.dateFormatter stringFromDate:photo.creationDate];
    cell.photoDateLabel.text = date;
}

但是這樣的代碼會讓 data source 變得混亂,因爲它向 data source 暴露了 cell 的設計。最好分解出來,放到 cell 類的一個 category 中。

@implementation PhotoCell (ConfigureForPhoto)

- (void)configureForPhoto:(Photo *)photo
{
    self.photoTitleLabel.text = photo.name;
    NSString* date = [self.dateFormatter stringFromDate:photo.creationDate];
    self.photoDateLabel.text = date;
}

@end

有了上述代碼後,我們的 data source 方法就變得簡單了。

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:PhotoCellIdentifier];
    [cell configureForPhoto:[self itemAtIndexPath:indexPath]];
    return cell;
}

在我們的示例代碼中,table view 的 data source 已經分解到單獨的類中了,它用一個設置 cell 的 block 來初始化。這時,這個 block 就變得這樣簡單了:

TableViewCellConfigureBlock block = ^(PhotoCell *cell, Photo *photo) {
    [cell configureForPhoto:photo];
};

讓 Cells 可複用

有時多種 model 對象需要用同一類型的 cell 來表示,這種情況下,我們可以進一步讓 cell 可以複用。首先,我們給 cell 定義一個 protocol,需要用這個 cell 顯示的對象必須遵循這個 protocol。然後簡單修改 category 中的設置方法,讓它可以接受遵循這個 protocol 的任何對象。這些簡單的步驟讓 cell 和任何特殊的 model 對象之間得以解耦,讓它可適應不同的數據類型。

在 Cell 內部控制 Cell 的狀態

如果你想自定義 table views 默認的高亮或選擇行爲,你可以實現兩個 delegate 方法,把點擊的 cell 修改成我們想要的樣子。例如:

- (void)tableView:(UITableView *)tableView
        didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.photoTitleLabel.shadowColor = [UIColor darkGrayColor];
    cell.photoTitleLabel.shadowOffset = CGSizeMake(3, 3);
}

- (void)tableView:(UITableView *)tableView
        didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.photoTitleLabel.shadowColor = nil;
}

然而,這兩個 delegate 方法的實現又暴露了 cell 如何實現的具體細節。如果我們想替換或重新設計 cell,我們必須改寫 delegate 代碼。View 的實現細節和 delegate 的實現交織在一起了。相反,我們應該把這些細節移到 cell 自身中去。

@implementation PhotoCell
// ...
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    if (highlighted) {
        self.photoTitleLabel.shadowColor = [UIColor darkGrayColor];
        self.photoTitleLabel.shadowOffset = CGSizeMake(3, 3);
    } else {
        self.photoTitleLabel.shadowColor = nil;
    }
}
@end

總的來說,我們在努力把 view layer 和 controller layer 的實現細節分離開。delegate 肯定得清楚一個 view 該顯示什麼狀態,但是它不應該瞭解如何修改 view tree 或者給 subviews 設置哪些屬性以獲得正確的狀態。所有這些邏輯都應該封裝到 view 內部,然後給外部提供一個簡單地 API。

控制多個 Cell 類型

如果一個 table view 裏面有多種類型的 cell,data source 方法很快就難以控制了。在我們示例程序中,photo details table 有兩種不同類型的 cell:一個用於顯示幾個星,另一個用來顯示一個鍵值對。爲了劃分處理不同 cell 類型的代碼,data source 方法簡單地通過判斷 cell 的類型,把任務派發給其他指定的方法。

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = self.keys[(NSUInteger) indexPath.row];
    id value = [self.photo valueForKey:key];
    UITableViewCell *cell;
    if ([key isEqual:PhotoRatingKey]) {
        cell = [self cellForRating:value indexPath:indexPath];
    } else {
        cell = [self detailCellForKey:key value:value];
    }
    return cell;
}

- (RatingCell *)cellForRating:(NSNumber *)rating
                    indexPath:(NSIndexPath *)indexPath
{
    // ...
}

- (UITableViewCell *)detailCellForKey:(NSString *)key
                                value:(id)value
{
    // ...
}

編輯 Table View

Table view 提供了易於使用的編輯特性,允許你對 cell 進行刪除或重新排序。這些事件,都可以讓 table view 的 data source 通過 delegate 方法得到通知。因此,通常我們能在這些 delegate 方法中看到對數據的進行修改的操作。

修改數據很明顯是屬於 model layer 的任務。Model 應該爲諸如刪除或重新排序等操作暴露一個 API,然後我們可以在 data source 方法中調用它。這樣,controller 就可以扮演 view 和 model 之間的協調者 ( coordinator ) ,而不需要知道 model 層的實現細節。並且還有額外的好處,model 的邏輯也變得更容易測試,因爲它不再和 view controllers 的任務混雜在一起了。

總結

Table view controllers(以及其他的 controller 對象!)應該在 model 和 view 對象之間扮演協調者和調解者的角色。它不應該關心明顯屬於 view layer 或 model layer 的任務。你應該始終記住這點,這樣 delegate 和 data source 方法會變得更小巧,最多包含一些簡單地樣板代碼。

這不僅減少了 table view controllers 那樣的大小和複雜性,而且還把業務邏輯和 view 的邏輯放到了更合適的地方。Controller layer 的裏裏外外的實現細節都被封裝成了簡單地 API,最終,它變得更加容易理解,也更利於團隊協作。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章