做過自訂 UITableViewCell 的人,大概都遇過這個難題:Cell 裡有個輪播相簿,點擊某張圖想跳轉到下一頁,卻發現 Cell 類別裡根本没法直接 push 一個新的 view controller。這時,delegate(協議)就是最經典的解法。本文用一個實際案例,完整示範 Cell 如何透過協議把「點了第幾張圖」回傳給控制器。
整個 Cell 裡放了一個 iCarousel 輪播控件(可左右滑動多張圖),它的代理寫在自訂 Cell 類裡。現在需求是:點擊某張圖,進入下一個頁面。但點擊事件都進到了 Cell 類的代理方法裡,而 Cell 類裡直接寫 [self.navigationController pushViewController:show animated:YES]; 是行不通的。
做法是——當使用者點擊某張圖時,在 Cell 的 iCarousel 代理方法 didSelectItemAtIndex: 中,把 index 透過協議傳給 StarShowViewController,再由控制器來執行 push 動作。
#import <Foundation/Foundation.h>
@protocol ImageItemDelegate <NSObject>
-(void)passItem:(NSString*)index; // 把點擊的是第幾個 image 的 index 傳過來
@end
#import "ImageItemDelegate.h"
@interface StarShowViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, ImageItemDelegate> {
UITableView *starTableView;
NSMutableArray *starArray;
}
#import "ImageItemDelegate.h"
@interface StarShowTableViewCell : UITableViewCell <iCarouselDataSource, iCarouselDelegate, UIGestureRecognizerDelegate>
@property(nonatomic, retain) NSObject <ImageItemDelegate> *itemDelegate; // 宣告一個代理
@end
// 選取某個 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 傳回控制器
}
- (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 模式,你就能應付絕大多數父子物件溝通的場景。