在開發中,我們常會遇到這樣的情境:某個畫面主要由一個 UITableView 構成,而每個 Cell 內部又用 iCarousel 做了一組可左右滑動的圖片輪播。當使用者點擊其中一張圖片時,我們希望跳到下一個詳情頁。問題在於,點擊事件最先觸發的是 Cell 內部 iCarousel 的代理方法,而 Cell 本身並不適合直接執行 pushViewController 這類導航操作。
這時,最得體的解法就是透過「代理(Delegate)協議」把點擊的 index 回傳給持有它的控制器,再由控制器完成頁面跳轉。以下我用一個完整範例說明整個流程。
先建立一個協議檔案 ImageItemDelegate.h,用來約定傳值的方法:
#import <Foundation/Foundation.h> @protocol ImageItemDelegate <NSObject> // 把點擊的是第幾張 image 的 index 傳出去 -(void)passItem:(NSString *)index; @end
在 StarShowViewController.h 中引入協議並宣告遵守:
#import "ImageItemDelegate.h"
@interface StarShowViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, ImageItemDelegate> {
UITableView *starTableView;
NSMutableArray *starArray;
}
@end
在 StarShowTableViewCell.h 裡聲明一個代理物件:
#import "ImageItemDelegate.h" @interface StarShowTableViewCell : UITableViewCell <iCarouselDataSource, iCarouselDelegate, UIGestureRecognizerDelegate> @property(nonatomic, retain) NSObject <ImageItemDelegate> *itemDelegate; @end
當使用者點擊某張圖片時,iCarousel 的代理方法會被觸發,我們在此把 index 交給代理:
// 選中某個 image item
-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
NSLog(@"index:%ld", (long)index);
NSString *str = [NSString stringWithFormat:@"%ld", (long)index];
// 透過代理把 index 傳回 StarShowViewController
[self.itemDelegate passItem:str];
}
在 StarShowViewController.m 建立 Cell 的 cellForRowAtIndexPath 方法中,把代理指向自己:
cell.itemDelegate = self; // 設定代理
最後實作協議方法,接收到 index 後完成頁面跳轉:
#pragma mark - ImageItemDelegate
// 從 cell 那邊拿到值
-(void)passItem:(NSString *)index {
ShowViewController *show = [[ShowViewController alloc] init];
show.imageIdex = index;
[self.navigationController pushViewController:show animated:YES];
}
其實,實現「點擊 Cell 內元件後跳頁」的方法有很多種:
本案例中,第一種方式在 Cell 封裝的情境下並不適用,因此選擇最能清楚表達「Cell 與控制器責任分離」的 delegate 方案,讓 Cell 只負責把事件與資料往外拋,跳轉邏輯則交由控制器統一處理。