gpt4 book ai didi

ios - 如何为不同类型的单元格重用 UITableViewCell

转载 作者:行者123 更新时间:2023-11-29 00:14:34 25 4
gpt4 key购买 nike

我有一个 UITableView,其中包含不同类型的单元格。常见的方法是使用不同的 UITableViewCell,并根据数据对象重用它们。

现在,我有 9 种不同类型的数据对象。但我的 View 类似于带有点赞按钮、评论按钮、用户图像和用户名的 Facebook 提要 View 。只有中心 View 会根据数据对象发生变化。

我的问题是,我应该为这些元素使用 9 种不同类型的具有共同类的单元格,还是应该使用一个单元格并在创建单元格时添加中心 View ?

目前我的方法是使用一个单元格并添加中心 View 。如果我们采用这种方法,UITableViewCell 是否会被重新使用?

最佳答案

如果您使用 reuseIdentifier: 初始化单元格并在表格 View 上使用 dequeueReusableCellWithIdentifier: 方法,表格 View 单元格将始终被重用。

就使用单个 UITableViewCell 子类还是多个子类而言,这取决于您的 9 种内容类型之间的差异程度。如果它们都包含相同的 UI 元素,则使用 1 个子类是有意义的。否则,您可以创建多个子类并仍然使用 dequeueReusableCellWithIdentifier: 重用单元格:只要您为每个子类传入不同的唯一标识符即可。每个子类都将被独立重用。

如果您使用多个单元类,您的 cellForRowAtIndexPath: 可能如下所示:

NSString *primaryCellID = @"PrimaryCellID";
NSString *secondaryCellID = @"SecondaryCellID";

if (someCondition) {
CustomTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:primaryCellID];

if (!cell) {
cell = [[CustomTableViewCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:primaryCellID];
}

return cell;
}
else {
CustomTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:secondaryCellID];

if (!cell) {
cell = [[CustomTableViewCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:secondaryCellID];
}

return cell;
}

关于ios - 如何为不同类型的单元格重用 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45591747/

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