我有按優先級排序的資料。我試圖在串列中顯示該資料:
priority 1
item with that priority
item with that priority
priority 2
item with that priority
item with that priority
所以我想用listwithsections來顯示優先級,然后在每個具有該優先級的專案下列出。
struct PriorityView: View {
@EnvironmentObject private var taskdata: DataModel
@State var byPriotity: Int
var body: some View {
List {
VStack(alignment: .leading, spacing: 12) {
// priority 3 is display all items in the list
if byPriotity == 3 {
ForEach(taskdata.filteredTasks(byPriority: byPriotity), id: \.id) { task in
Section(header: Text(getTitle(byPriority: task.priority)).font(.headline)) {
Text(task.title)
}
}
}
}
}
}
}
這只是創建一個串列,其中包含一個顯示優先級的部分,然后是專案的標題。這不是我想要輸出的。我開始閱讀section和一些文章(
將結構名稱更改為:
struct SectionOrdered : Identifiable {
var id: String { priority }
let priority: String
let tasks: [Task]
}
我試過的代碼是:
List {
VStack(alignment: .leading, spacing: 12) {
if byPriority == 3 {
ForEach(taskdata.sections) { task in
Section(header: task.priority) {
Text(task.title)
}
}
}
}
}
vadian 建議在課堂上過濾所有內容,但我不知道如何使用它。我試過了,但我在這里弄得更糟。
我想知道這是否可能。

uj5u.com熱心網友回復:
要將資料分組為部分,首先創建一個結構Section
struct Section : Identifiable {
var id : String { priority }
let priority : String
let tasks : [Task]
}
并在視圖模型中發布部分并將它們分組,例如在init方法中。
final class DataModel: ObservableObject {
@AppStorage("tasksp") public var tasks: [Task] = []
@Published var sections = [Section]()
init() {
let grouped = Dictionary(grouping: tasks, by: \.priority)
let sortedKeys = grouped.keys.sorted()
self.sections = sortedKeys.map{Section(priority: getTitle(byPriority: $0), tasks: grouped[$0]!)}
}
func getTitle(byPriority: Int) -> String {
switch byPriority {
case 0: return "Important"
case 1: return "Tomorrow"
default: return "Someday"
}
}
....
好處是將所有不必要的資料處理都排除在視圖之外。
在視圖中顯示資料
ForEach(taskdata.sections) { section in
Section {
ForEach(section.tasks) { task in
Text(task.title)
}
} header: {
Text(section.priority)
.font(.headline)
}
}
如果要將過濾后的資料分組到部分中,請先過濾它,然后再分組。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471661.html
下一篇:嘗試解碼動態JSON回應
