gpt4 book ai didi

ios - Swift 4 - 随机顺序的多个表格 View 单元格类型

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:19 26 4
gpt4 key购买 nike

我正在创建一个待办事项列表应用程序,在列表 TableView 中,需要有 3 种类型的 TableView 单元格。一个用于任务,一个用于事件,一个用于提醒。每个单元格内部都有不同的元素(多个标签、不同的图像等...)

我希望能够在同一个表格 View 中使用 3 种不同的单元格类型。

我创建了 3 个 UITableViewCell 类,每个类都有单元格约束和内部设置。在我的核心数据模型中,有 3 个实体。一个用于任务、事件和提醒。

此外,它是一个待办事项列表应用程序,因此单元格应按任意顺序排列,每个自定义单元格的数量也是任意的。

所以使用:

if indexPath.row == 0 {...} etc...etc...

不可行。

任何有关如何实现此目标的帮助或想法将不胜感激。

最佳答案

您需要根据您拥有的项目类型而不是根据 indexPath 将单元格出队。

您的事件/提醒/任务有三个结构/类:

struct Event { ... }
struct Reminder { ... }
struct Task { ... }

和:

var myTableViewArray: [Any] //Array of either Event, Reminder, Task objects.

tableView(_:cellForRowATt:) 中:

func tableView(_ tableView: UITableView, 
cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let object = myTableViewArray[indexPath.row]
if let event = object as? Event {
let cell = tableView.dequeueReusableCell(withIdentifier: "EventCellId" for:indexPath) as EventCell
//configure cell with event
return cell
} else if let task = object as? Task {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCellId" for:indexPath) as TaskCell
//configure cell with task
return cell
} else if let reminder = object as? Reminder {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReminderCellId" for:indexPath) as ReminderCell
//configure cell with reminder
return cell
} else {
//We shouldn't get into this case, but return an UITableViewCell here?
}

}

如果您有相同的对象,或者因为您添加了一个模拟该对象的协议(protocol),但如果它是一个事件/提醒/任务,则具有一个属性,例如枚举:

enum Type {
case event
case reminder
case task
}

struct CustomObject {
let type: Type
}

然后,代替:

if let event = object as? Event {}
else if let task = object as? Task {}
else if let reminder = object as? Reminder {}

只需做一个简单的切换:

switch object.type {
case .event:
//Dequeue the EventCell
case .task:
//Dequeue the TaskCell
case .reminder:
//Dequeue the ReminderCell
}

关于ios - Swift 4 - 随机顺序的多个表格 View 单元格类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457437/

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