gpt4 book ai didi

ios - 如何重构UITableViewCell配置代码?

转载 作者:行者123 更新时间:2023-11-29 03:40:58 27 4
gpt4 key购买 nike

我有一个带有单个自定义表格 View 单元格的表格 View ,随着时间的推移,它导致了一些复杂的结构,我希望能够简化和改进它。基本上在当前的形式中,单元格的左侧和右侧有图像和按钮,中间可能有两个不同的标签。

单元格是根据它们所代表的条目、 TableView 的部分和 TableView 的状态来配置的,因此 cellForRowAtIndexPath 和 willDisplayCell 中的代码都变得非常困惑。配置包括隐藏/取消隐藏非标签 subview 和可能更改 UILabels 的框架。

您建议如何构建和改进此类代码,以及您何时开始使用不同的自定义单元类?

最佳答案

我会为您拥有的每个条目类型创建自定义子类。在每个单元格子类上创建一个方法,名为

-(void)configureCell:(Entry *)entry
{
//do configuration stuff here
}

然后在 cellForRowAtIndexPath 中执行以下操作:

Entry *entry = self.entryArray[indexPath.row];
UITableViewCell *cell;
switch( entry.entryType )
{
case EntryTypeOne:
CellTypeOne *cCell = (CellTypeOne *)[tableView dequeueReusableCellWithIdentifier:@"CellTypeOne" forIndexPath:indexPath
[cCell configureCell:entry];
cell = cCell;
break;
case EntryTypeTwo:
CellTypeTwo *cCell = (CellTypeTwo *)[tableView dequeueReusableCellWithIdentifier:@"CellTypeTwo" forIndexPath:indexPath
[cCell configureCell:entry];
cell = cCell;
break;
}

return cCell;

只是一些想法,因为我实际上不知道您的代码是如何设置的,也不知道如何区分条目类型。

关于ios - 如何重构UITableViewCell配置代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com