How to properly group a list fetched from CoreData by date?

后端 未结 1 902
囚心锁ツ
囚心锁ツ 2020-12-06 06:07

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 a

相关标签:
1条回答
  • 2020-12-06 06:56

    You may try the following, It should work in your situation.

      @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
      }
    
        func update(_ result : FetchedResults<Todo>)-> [[Todo]]{
          return  Dictionary(grouping: result){ (element : Todo)  in
                dateFormatter.string(from: element.date!)
          }.values.map{$0}
        }
    
    
      var body: some View {
        VStack {
          List {
            ForEach(update(todos), id: \.self) { (section: [Todo]) in
                Section(header: Text( self.dateFormatter.string(from: section[0].date!))) {
                    ForEach(section, id: \.self) { todo in
                HStack {
                Text(todo.title ?? "")
                Text("\(todo.date ?? Date(), formatter: self.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")
          })
        }
      }
    
    0 讨论(0)
提交回复
热议问题