我在管理应用程序的 UI 时遇到问题。该应用程序利用 UITableView,具有多个原型(prototype)单元。 一切正常,我有这样的:
TypeACell.h + m files
TypeBCell.h + m files
TypeBCell.h + m files
etc.
我在 Storyboard 的 UITableView 中创建了原型(prototype)单元格,并且有大约 6 个原型(prototype)单元格,每个单元格都连接到特定类型的单元格。
事实是,每个自定义单元格中至少有 4 个元素可以在每个单元格中重复使用。 我们假设每个自定义单元格中只有 2 个元素不同。
为了便于讨论,让我们想象一下单元格如下所示:
TypeACell
row1
row2
rowCustomA1
rowCustomA2
TypeBCell
row1
row2
rowCustomB1
rowCustomB2
etc.
然后在 cellForRowAtIndexPath 中我有类似的东西:
if(array[i] == TypeA){
TypeACell *cell = [tblView dequeueReusableCellWithIdentifier:typeAIdentifier];
set row1,row2, rowCustomA1, rowCustomA2;
display TypeACell
}
else if(array[i] == TypeB){
TypeBCell *cell = [tblView dequeueReusableCellWithIdentifier:typeBIdentifier];
set row1,row2, rowCustomB1, rowCustomB2;
display TypeBCell
}
问题是,使用这种实现方式,我必须修改 12 个位置才能进行更改,这对于所有单元格来说都是常见的。我正在寻找一种修改我的实现的方法。我一直想知道是否存在一些特定于 Objective-C 的方法可以帮助我处理这些废话。您能提供一下您的经验和建议吗?
编辑: 为每个“if”添加了单元格初始化。目前,这是我在基于继承的实现中唯一无法解决的问题。
最佳答案
这就是您可以从继承中受益的地方:使用所有细胞类型通用的元素创建一个基类,然后将各个细胞类型作为其子类,如下所示:
@interface CommonCell : UITableViewCell
... // Common properties
@end
@interface TypeACell : CommonCell
... // Properties specific to A
@end
@interface TypeBCell : CommonCell
... // Properties specific to B
@end
@interface TypeCCell : CommonCell
... // Properties specific to C
@end
现在您的循环可以更改如下:
for(iteration over array){
CommonCell *cell = ...
... // set common elements
set row1, row2
if(array[i] == TypeA){
set rowCustomA1, rowCustomA2;
}
else if(array[i] == TypeB){
set rowCustomB1, rowCustomB2;
}
...
display cell
}
关于ios - 如何有效地实现多个内容略有不同的自定义 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358330/