欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS复数cell下优雅的代码结构详解

程序员文章站 2023-01-11 10:49:13
前言 最近换了新工作,第一个需求是写几个列表。 简单的uitableview+cell,但毕竟是入职后的第一个需求感觉要被review,所以还是想尽量弄得优雅一...

前言

最近换了新工作,第一个需求是写几个列表。

简单的uitableview+cell,但毕竟是入职后的第一个需求感觉要被review,所以还是想尽量弄得优雅一点。

下面话不多说了,来一起看看详细的介绍吧

需求

iOS复数cell下优雅的代码结构详解

一个页面,可能出现多种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;
}

结尾

人总是不断成长的,这个方案目前是我觉得比较不错的。

如果有大佬愿意指教或者探讨,不胜感激

iOS复数cell下优雅的代码结构详解

demo可以自取 (本地下载

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。