【发布时间】:2020-03-29 12:46:08
【问题描述】:
为了简单起见,假设我想创建一个简单的待办事项应用程序。我的 xcdatamodeld 中有一个实体 Todo,其属性为 id、title 和 date,以及以下 swiftui 视图(如图所示):
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")
})
}
}
}
待办事项在获取时按日期排序,并显示在如下列表中:
我想根据每个待办事项各自的日期对列表进行分组(样机):
据我了解,这可以与 init() 函数中的字典一起使用,但是我想不出任何远程有用的东西。有没有一种有效的数据分组方式?
【问题讨论】:
标签: ios swift core-data swiftui