为了简单起见,假设我想创建一个简单的待办事项应用程序。我的 xcdatamodeld 中有一个实体 Todo ,其属性id
, title
and 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 15 更新
SwiftUI
现在内置了对分段获取请求的支持List
通过@SectionedFetchRequest
属性包装器。该包装器减少了对核心数据列表进行分组所需的样板数量。
示例代码
@Environment(\.managedObjectContext) var moc
@State private var date = Date()
@SectionedFetchRequest( // Here we use SectionedFetchRequest
entity: Todo.entity(),
sectionIdentifier: \.dateString // Add this line
sortDescriptors: [
SortDescriptor(\.date, order: .forward)
]
) var todos: SectionedFetchResults<Todo>
var body: some View {
VStack {
List {
ForEach(todos) { (section: [Todo]) in
Section(section[0].dateString!))) {
ForEach(section) { todo in
HStack {
Text(todo.title ?? "")
Text("\(todo.date ?? Date(), formatted: todo.dateFormatter)")
}
}
}
}.id(todos.count)
}
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 Todo
类还可以重构以包含获取日期字符串的逻辑。作为奖励,我们还可以使用.formatted
贝塔法Date
来产生相关的String
.
struct Todo {
...
var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter
}()
var dateString: String? {
formatter.string(from: date)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)