目標:我想按照Todo我已經達到的截止日期顯示專案串列。但我也想Categories在 Todo 專案串列上方的同一個視圖上顯示不同物體的串列。類別是將您帶到過濾到該類別的待辦事項串列的按鈕。我設定了一個 Category 的關系來有很多 todos。如何更改我的 FetchRequest 以支持添加的關系?
這是SectionedFetchRequest下面的電流。如果我嘗試為類別添加新的 FetchRequest,我會崩潰。
@SectionedFetchRequest(entity: Todo.entity(),
sectionIdentifier: \.dueDateRelative,
sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)],
predicate: nil,
animation: Animation.linear)
var sections: SectionedFetchResults<String, Todo>
ForEach(sections) { section in
Section(header: Text(section.id.description)) {
ForEach(section) { todo in
TodoRowView(todo: todo)
.frame(maxWidth: .infinity)
.listRowSeparator(.hidden)
}
.onDelete { indexSet in
deleteTodo(section: Array(section), offsets: indexSet)
}
}
}
// Causes Crash when added to existing Fetch Request
//@FetchRequest(entity: Category.entity(), sortDescriptors: []) var categories: FetchedResults<Category>


uj5u.com熱心網友回復:
你可能想多了。如果您sectionIdentifier為該類別添加一個,則可以相對容易地提供該選項。
變數看起來像這樣
extension Todo{
@objc
var categoryTitle: String{
self.relationship?.title ?? "no category"
}
}
然后添加一些變數到 View
//Dictionary to store sort options
let sortOptions: [String: KeyPath<Todo, String>] = ["due date": \Todo.dueDateRelative, "category":\Todo.categoryTitle]
//Variable to use to filter list
@State var selectedSection: String = ""
//filter the `sections` by the selected section
//You can use nsPredicate too
var filteredSections: [SectionedFetchResults<String, Todo>.Element] {
sections.filter({ val in
if !selectedSection.isEmpty {
return val.id == selectedSection
}else{
return true
}
})
}
然后給用戶一些按鈕來選擇
//Give the user sort options
Menu("sort"){
ForEach(Array(sortOptions.keys).sorted(by: <), id:\.self, content: { key in
Button(key, action: {
sections.sectionIdentifier = sortOptions[key]!
selectedSection = ""
})
})
}
//Give the user section options
Picker("sections", selection: $selectedSection, content: {
ForEach(sections, content: {section in
Text(section.id).tag(section.id)
})
Text("all").tag("")
}).pickerStyle(.segmented)
該ForEach會自動顯示用戶選擇
ForEach(filteredSections) { section in
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393679.html
