前言
最近換了新工作,第一個需求是寫幾個列表。
簡單的UITableView+Cell,但畢竟是入職後的第一個需求感覺要被review,所以還是想盡量弄得優雅一點。
需求
一個頁面,可能出現多種cell。
這個需求應該是很常見的,需要解決的問題是如何讓多個cell能夠共同響應同一個方法,這樣外部不需要知道具體的cell種類,只要調用同一個方法進行配置即可。
問了問朋友們大家基本上是兩派。
協議
基類
我個人以前也是用協議對多個cell進行約束的,通過讓cell遵循同一個協議並實現協議方法,讓外部達到統一配置的效果。
//cell共同遵循這個協議
@protocol ModuleACellConfigPropotol <NSObject>
- (void)configCellWithModel:(KTModel *)model;
@end
通過協議調用方法
UITableViewCell<ModuleACellConfigPropotol> * cell= [tableView dequeueReusableCellWithIdentifier:cellID];
if ([cell respondsToSelector:@selector(configCellWithModel:)]) {
[cell configCellWithModel:model];
}
對於基類繼承,大家普遍反映很噁心,準備重構,所以就不考慮了。
耦合
標準的MVC情況下, cell的配置方法,應該長這樣:
@interface KTTableViewCell00 : UITableViewCell
- (void)configShowViewWithTitle00:(NSString *)title;
@end
@interface KTTableViewCell01 : UITableViewCell
- (void)configShowViewWithTitle01:(NSString *)title;
@end
外部賦值也不應該把model傳遞給cell,而是隻傳遞cell指定的參數
[cell configShowViewWithTitle01:model.title];
而協議,爲了達到統一配置,必須使用同一個方法進行約束。而cell們實際上的充要參數並不相同,所以只能將整個model作爲參數進行傳遞。
@protocol ModuleACellConfigPropotol <NSObject>
- (void)configCellWithModel:(KTModel *)model;
@end
解耦
通過協議約束的方式,已經能夠成功實現統一配置。
但有一個問題隨之而來,這樣cell就與model產生了耦合,導致cell無法複用。
從結果上來看,這樣並不完美。
要解決這個問題,我覺得在cell與協議之間,又添加了一層適配器是個不錯的方案。
而這個適配器,我使用了Category進行實現。
@interface KTTableViewCell00 (ModuleA) <ModuleACellConfigPropotol>
@end
@implementation KTTableViewCell00 (ModuleA)
- (void)configCellWithModel:(KTModel *)model {
[self configShowViewWithTitle00:model.title];
}
@end
最後調用起來 :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
KTModel *model = self.dataArr[indexPath.row];
NSString * cellID = model.identifier;
UITableViewCell<ModuleACellConfigPropotol> * cell= [tableView dequeueReusableCellWithIdentifier:cellID];
if ([cell respondsToSelector:@selector(configCellWithModel:)]) {
[cell configCellWithModel:model];
}
return cell;
}
結尾
人總是不斷成長的,這個方案目前是我覺得比較不錯的。
如果有大佬願意指教或者探討,不勝感激