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
}
}