Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Created October 20, 2024 20:14
Show Gist options
  • Save colinfwren/8906099167d85d91a8e4936b4502c540 to your computer and use it in GitHub Desktop.
Save colinfwren/8906099167d85d91a8e4936b4502c540 to your computer and use it in GitHub Desktop.
import SwiftUI
import SwiftData
import Algorithms
struct EntryListView: View {
@Query(sort: \Entry.created, order: .reverse) private var entries: [Entry]
let entryDateFormatter = DateFormatter()
let sectionDateFormatter = DateFormatter()
init() {
entryDateFormatter.dateFormat = "EEEE, dd MMM yyyy"
sectionDateFormatter.dateFormat = "MMM yyyy"
}
var body: some View {
List {
ForEach(sectionedEntries, id: \.self.0) { title, entries in
Section(title) {
ForEach(entries) { entry in
VStack(alignment: .leading, spacing: 4) {
Text(entry.text)
Text(entryDateFormatter.string(from: entry.created))
}
}
}
}
}
}
var sectionedEntries: [(String, [Entry])] {
chunkEntries(entriesToChunk: entries)
}
func chunkEntries(entriesToChunk: [Entry]) -> [(String, [Entry])] {
let chunks = entriesToChunk.chunked(on: {
Calendar.current.dateComponents([.year, .month], from: $0.created)
})
return chunks.map {
let chunkDate = Calendar.current.date(from: $0.0)
return (sectionDateFormatter.string(from: chunkDate!), Array($0.1))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment