For the sake of simplicity lets assume I want to create a simple todo app. I have an entity Todo in my xcdatamodeld with the properties id
, title
and date
, and the following swiftui view (example pictured):
import SwiftUI
struct ContentView: View {
@Environment(.managedObjectContext) var moc
@State private var date = Date()
@FetchRequest(
entity: Todo.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: Todo.date, ascending: true)
]
) var todos: FetchedResults<Todo>
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter
}
var body: some View {
VStack {
List {
ForEach(todos, id: .self) { todo in
HStack {
Text(todo.title ?? "")
Text("(todo.date ?? Date(), formatter: self.dateFormatter)")
}
}
}
Form {
DatePicker(selection: $date, in: ...Date(), displayedComponents: .date) {
Text("Datum")
}
}
Button(action: {
let newTodo = Todo(context: self.moc)
newTodo.title = String(Int.random(in: 0 ..< 100))
newTodo.date = self.date
newTodo.id = UUID()
try? self.moc.save()
}, label: {
Text("Add new todo")
})
}
}
}
The todos are sorted by date upon fetching, and are displayed in a list like this:
I want to group the list based on each todos respective date as such (mockup):
From my understanding this could work with Dictionaries in the init()
function, however I couldn't come up with anything remotely useful. Is there an efficient way to group data?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…