前言
最近换了新工作,第一个需求是写几个列表。
简单的UITableView+Cell,但毕竟是入职后的第一个需求感觉要被review,所以还是想尽量弄得优雅一点。
需求
一个页面,可能出现多种cell。
这个需求应该是很常见的,需要解决的问题是如何让多个cell能够共同响应同一个方法,这样外部不需要知道具体的cell种类,只要调用同一个方法进行配置即可。
问了问朋友们大家基本上是两派。
协议
基类
我个人以前也是用协议对多个cell进行约束的,通过让cell遵循同一个协议并实现协议方法,让外部达到统一配置的效果。
//cell共同遵循这个协议 @protocol ModuleACellConfigPropotol- (void)configCellWithModel:(KTModel *)model; @end 通过协议调用方法 UITableViewCell * 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- (void)configCellWithModel:(KTModel *)model; @end
解耦
通过协议约束的方式,已经能够成功实现统一配置。
但有一个问题随之而来,这样cell就与model产生了耦合,导致cell无法复用。
从结果上来看,这样并不完美。
要解决这个问题,我觉得在cell与协议之间,又添加了一层适配器是个不错的方案。
而这个适配器,我使用了Category进行实现。
@interface KTTableViewCell00 (ModuleA)@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* cell= [tableView dequeueReusableCellWithIdentifier:cellID]; if ([cell respondsToSelector:@selector(configCellWithModel:)]) { [cell configCellWithModel:model]; } return cell; }
结尾
人总是不断成长的,这个方案目前是我觉得比较不错的。
如果有大佬愿意指教或者探讨,不胜感激
作者:kirito_song
链接:https://www.jianshu.com/p/723e8435586d
本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/ios-fushucellxiayouyadedaimajiegou.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:4 月 1, 2019 at 06:40 下午