gpt4 book ai didi

ios - 如何用二维数组填充表格 View ?

转载 作者:行者123 更新时间:2023-11-28 13:43:13 25 4
gpt4 key购买 nike

我有 2 个数组:roomsArray:[Auditorie]groupsArray:[Group]。我将它们附加到 roomsAndGroups:[[Any]] 中。问题是如何使用 2D 数组或 2 个不同类型的数组填充 tableView。

struct Auditorie: Codable {
let id: Int
let name: String
let building: Building
}

struct Building: Codable {
let name: String
let abbr: String
}

struct Group: Codable {
let id: Int
let name: String
}

fileprivate var roomsArray:[Auditorie] = []
fileprivate var groupsArray:[Group] = []
fileprivate var roomsAndGroups:[[Any]] = []


数组看起来像这样

[[PolyStudents.Group(id: 26025, name: "23254/1"), PolyStudents.Group(id: 26605, name: "43325/2"), PolyStudents.Group(id: 26615, name: "43325/3"), PolyStudents.Group(id: 27121, name: "53325/3"), PolyStudents.Group(id: 26055, name: "33254/1"), PolyStudents.Group(id: 26056, name: "33253/1"), PolyStudents.Group(id: 25976, name: "13254/1"), PolyStudents.Group(id: 26026, name: "23255/1"), PolyStudents.Group(id: 26604, name: "43325/1"), PolyStudents.Group(id: 26057, name: "33255/1")], [PolyStudents.Auditorie(id: 1579, name: "1325", building: PolyStudents.Building(name: "50 учебный корпус", abbr: "50 уч.к")), PolyStudents.Auditorie(id: 1641, name: "325", building: PolyStudents.Building(name: "11-й учебный корпус", abbr: "11 к."))]]

最佳答案

我可以看到两种方法可以帮助您实现这一目标。首先,根据 ielyamani 的评论,您可以使用通用协议(protocol)。其次,您可以将您的类型包装在一个枚举中。

选项 1

假设 name 属性是您的类型中唯一常见的。所以你可以创建一个像这样的协议(protocol):

protocol Nameable {
var name: String { get }
}

然后让你的类型符合:

struct Auditorie: Codable, Nameable {
let id: Int
let name: String
let building: Building
}

struct Building: Codable, Nameable {
let name: String
let abbr: String
}

struct Group: Codable, Nameable {
let id: Int
let name: String
}

因此您的 roomsAndGroups 现在应该由 Nameable 组成:

var roomsAndGroups: [[Nameable]]()

并且在您的 TableView 的数据源方法中,您可以获取那些可命名对象并填充您的表:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var nameable = roomsAndGroups[indexPath.section][indexPath.row]

...

cell.textLabel?.text = nameable.name
return cell
}

选项 2

用枚举包装你的类型,例如:

enum Wrapper {
case auditorie(Auditorie)
case group(Group)
}

您的 roomsAndGroups 和 TableView 数据源方法相应更改:

var roomsAndGroups: [[Wrapper]]()

...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var wrapper = roomsAndGroups[indexPath.section][indexPath.row]
switch wrapper {
case .auditorie(let auditorie):
// Handle cell dequeuing with auditorie object
case .group(let group):
// Handle cell dequeuing with group object
}
}

关于ios - 如何用二维数组填充表格 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767574/

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