gpt4 book ai didi

swift - 在 cellforitem swift 中显示两种不同类型的单元格

转载 作者:行者123 更新时间:2023-11-28 11:52:30 24 4
gpt4 key购买 nike

我有两个数组,一个包含字符串,一个包含自定义对象。

我分别创建了两个不同的单元格。我已将两个数组的内容添加到第三个通用数组 Any 中。我在 cellForItem 中使用第三个数组 (combinedArray)。

var customObjectArray: [customObject] = []
var stringArray = [String]()
var combinedArray = [Any]()

if combinedArray[indexPath.row] is CustomObject {


cell1.LabelName.text = customObjectArray[indexPath.row].caption
cell1.iconView.image = customObjectArray[indexPath.row].icon
return cell1
} else {

let stringName = stringArray[indexPath.row]
cell2.LabelName.setTitle(stringName for: UIControlState())
return cell2
}

假设 customObjectArray 有 13 个对象,stringObjectArray 有 17 个对象。我希望每个数组都有一个单独的计数器,以便正确填充它们。它现在的工作方式:

combinedArray 首先填充所有一种类型(即首先填充 13 个 customObjectArray),然后再填充下一个类型(即 17 个 stringObjects)。组合数组的顺序不一定很重要,因为我可能会在到达 cellforitem 之前的某个时候随机播放。因此,当 cellforItem 遍历前 13 个对象时,indexpath.row = 14,当它到达第二类对象时,它会跳过前 13 个对象并显示 stringObject 的第 14 个元素(很明显)。

我不知道如何从第二个数组的开头而不是 indexPath.row 的当前位置开始。

我在这里可能完全偏离基础,可能应该使用两个部分或类似性质的东西,但我是 iOS 开发人员的新手,因此欢迎任何指导。

最佳答案

另一种选择是将不同的数据类型包含在一个枚举中,然后按照您想要的任何顺序将所有数据添加到组合数组中。

enum DataHolder {
case stringType(String)
case customType(CustomObject)
}

var combinedArray: [DataHolder]

这为您提供了一种数据类型和一种区分单元格类型的方法。

cellForItem 内部对 combinedArray 执行切换

switch combinedArray[indexPath.row] {
case .stringType(let stringValue):
let cell = tableView.dequeueReusableCell(withIdentifier: "StringCell", for: indexPath) as! StringObjectCell
cell.labelName.text = stringValue
case .customType(let customData):
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomObjectCell
cell.labelName.text = customData.caption
cell.iconView.image = customData.icon

关于swift - 在 cellforitem swift 中显示两种不同类型的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51688735/

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