5

I'm building a SwiftUI app where it shows a list of values containing their associated date and duration. At the moment the ContentView is just listing all the values (date ascending).

What I would like to achieve is so that entities are grouped by date and into their relevant sections, for example:

Current

  • Section: "date"
    • Duration: 50, Date: 1st Jan
    • Duration: 48, Date: 1st Jan
    • Duration: 21, Date: 2nd Jan
    • Duration: 57, Date: 3rd Jan

Aim

  • Section: "1st Jan"
    • Duration: 50, Date: 1st Jan
    • Duration: 48, Date: 1st Jan
  • Section: "2nd Jan"
    • Duration: 21, Date: 2nd Jan
  • Section: "3rd Jan"
    • Duration: 57, Date: 3rd Jan

Any help is greatly appreciated, many thanks.

Code

// MARK: - ContentView

struct ContentView: View {

    // MARK: - Variables

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: EntityCore.fetch()) var entities

    // MARK: - Body

    var body: some View {

        NavigationView {
            List {
                Section(header: Text("Date")) {
                    ForEach(entities) { (entity) in
                        EntityView(entity: entity)

                    }
                }

            }.listStyle(GroupedListStyle())
             .navigationBarTitle(Text("Entities"))

        }
    }
}

// MARK: - PlankCore

public class EntityCore: NSManagedObject, Identifiable {

    // MARK: - Variables

    @NSManaged public var duration: Int64
    @NSManaged public var date: Date?

    // MARK: - Fetch

    static func fetch() -> NSFetchRequest<EntityCore> {

        let request = EntityCore.fetchRequest() as! NSFetchRequest<EntityCore>
        request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]

        return request

    }
}
WH48
  • 737
  • 1
  • 7
  • 24
  • 1
    This has been answered in a newer question: https://stackoverflow.com/questions/59180698/how-to-properly-group-a-list-fetched-from-coredata-by-date – pjh68 Dec 28 '19 at 15:10
  • See how @SectionedFetchRequest can help you with sectioning: https://stackoverflow.com/a/74840941 – Paul B Dec 18 '22 at 14:18

0 Answers0