您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 協議實戰:用 delegate 讓自訂 Cell 與控制器溝通

編輯:iOS 相關資訊

做過自訂 UITableViewCell 的人,大概都遇過這個難題:Cell 裡有個輪播相簿,點擊某張圖想跳轉到下一頁,卻發現 Cell 類別裡根本没法直接 push 一個新的 view controller。這時,delegate(協議)就是最經典的解法。本文用一個實際案例,完整示範 Cell 如何透過協議把「點了第幾張圖」回傳給控制器。

問題描述

整個 Cell 裡放了一個 iCarousel 輪播控件(可左右滑動多張圖),它的代理寫在自訂 Cell 類裡。現在需求是:點擊某張圖,進入下一個頁面。但點擊事件都進到了 Cell 類的代理方法裡,而 Cell 類裡直接寫 [self.navigationController pushViewController:show animated:YES]; 是行不通的。

解決思路:用協議回傳 index

做法是——當使用者點擊某張圖時,在 Cell 的 iCarousel 代理方法 didSelectItemAtIndex: 中,把 index 透過協議傳給 StarShowViewController,再由控制器來執行 push 動作。

步驟一:定義協議 ImageItemDelegate.h

#import <Foundation/Foundation.h>

@protocol ImageItemDelegate <NSObject>

-(void)passItem:(NSString*)index;  // 把點擊的是第幾個 image 的 index 傳過來

@end

步驟二:控制器遵守協議 StarShowViewController.h

#import "ImageItemDelegate.h"

@interface StarShowViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, ImageItemDelegate> {
    UITableView *starTableView;
    NSMutableArray *starArray;
}

步驟三:Cell 宣告代理 StarShowTableViewCell.h

#import "ImageItemDelegate.h"

@interface StarShowTableViewCell : UITableViewCell <iCarouselDataSource, iCarouselDelegate, UIGestureRecognizerDelegate>

@property(nonatomic, retain) NSObject <ImageItemDelegate> *itemDelegate;  // 宣告一個代理

@end

步驟四:Cell 傳值 StarShowTableViewCell.m

// 選取某個 image item
-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"index:%ld", (long)index);
    NSString *str = [NSString stringWithFormat:@"%ld", (long)index];

    UIView *view = carousel.currentItemView;

    [self.itemDelegate passItem:str];  // 透過代理把 str 傳回控制器
}

步驟五:在 cellForRowAtIndexPath 設置代理 StarShowViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // ...
    cell.itemDelegate = self;  // 設置代理
    return cell;
}

步驟六:在控制器中完成跳轉

#pragma mark - ImageItemDelegate
// 從 Cell 那邊拿到值
-(void)passItem:(NSString *)index {
    ShowViewController *show = [[ShowViewController alloc] init];
    show.imageIdex = index;
    [self.navigationController pushViewController:show animated:YES];
}

結語:其實方法有很多種

這個問題的實現方式其實不少:① 直接在控制器裡給 Image 添加點擊事件;② 使用 delegate,在控制器裡實現點擊觸發;③ 用 block;④ 用事件響應者鏈處理。第一種在這個場景不太合適,第四種概念上較複雜,而 delegate 是 TableView Cell 溝通最經典、最推薦的做法——它讓 Cell 保持通用性,把「點擊後要做什麼」的決定權交還給控制器。理解了這套 delegate 模式,你就能應付絕大多數父子物件溝通的場景。

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