前言
最近換了新工作,第一個需求是寫幾個列表。
簡單的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;}
結尾
人總是不斷成長的,這個方案目前是我覺得比較不錯的。
如果有大佬愿意指教或者探討,不勝感激
Demo可以自取 (本地下載)
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。
新聞熱點
疑難解答