gpt4 book ai didi

ios - tableView 中的多个继承类

转载 作者:行者123 更新时间:2023-11-30 14:02:37 25 4
gpt4 key购买 nike

我正在从一组不同的继承类创建一个 tableView,但我似乎无法弄清楚将它们全部添加到 tableView 中的最佳方法是什么,而不创建多个数组,这并不理想?

让我们举一个经典的例子,我如何能够将多个不同的猫和狗对象添加到 tableView 中?最好的方法是什么?

class Pet {
var id: Int = 0
var name: String = ""

}

class Dog: Pet {
var Type: String = ""
}

class Cat: Pet {
var Type: String = ""
}

最佳答案

最直接的方法是在 UI 层中反射(reflect)您的模型。喜欢:

class PetTableViewCell {
}

class DogTableViewCell: PetTableViewCell {
}

class CatTableViewCell: PetTableViewCell {
}

然后在 TableView 中使用它们: this answer显示 UITableView

中两种不同单元格类型的用法

另一种方法是定义一个协议(protocol),该协议(protocol)描述模型类需要在单元中显示的行为,并在模型类中实现(或继承)它。

protocol MyTableViewCellDisplayable {
var Type: String
var Pic: Image
var Name: String
}

class MyTableViewCell {
func displayObject(obj: MyTableViewCellDisplayable);
}

class Pet: MyTableViewCellDisplayable {
}

class Dog: Pet {
}

class Cat: Pet {
}
...

正确解决方案的选择实际上取决于您的特定要求。

关于ios - tableView 中的多个继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806322/

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