Is it possible to have sections in a SwiftUI table? I cannot find any documentation or examples that show that it is.
Sections in SwiftUI Tables?
AFAIK, not directly in Table. When there are multiple columns, would you have section for a specific column or for all ?
It is possible in List. Cen you adapt your code to use List instead ?
I could use a List but it's not as powerful as a Table. I want to achieve something similar that you can find with Finder. It's most likely on Apple's list (no pun intended) already but had other priorities. Let's hope for iOS 18 and macOS 15!
I was able to do this by adding Section
for the @TableColumnBuilder
in this Table initializer.
A (reduced) code sample:
struct ImportTrackTable: View {
@EnvironmentObject var store: Store
@State var selectedTracks: Set<Track.ID> = .init()
// Sorting
@State private var sortOrder: [KeyPathComparator<Binding<Track>>] = [
.init(\.title.wrappedValue, order: .forward),
]
private let titleComparator = KeyPathComparator<Track>(\.title, order: .forward)
var body: some View {
Table(
of: Binding<Track>.self,
selection: $selectedTracks,
sortOrder: $sortOrder
) {
TableColumn(
"Title",
value: \Binding<Track>.wrappedValue,
comparator: titleComparator
) { trackBinding in
TrackTextField(text: trackBinding.title)
}
TableColumn(
"Genres",
value: \Binding<Track>.wrappedValue.genreList
)
} rows: {
Section("Unassigned") {
ForEach(
$store.tracks
.sorted(using: sortOrder)
.filter({ track in
// Cool filter logic
})
) { $track in
TableRow($track)
.draggable($track.wrappedValue)
}
}
Section("Assigned") {
ForEach(
$store.tracks
.sorted(using: sortOrder)
) { $track in
TableRow($track)
.draggable($track.wrappedValue)
}
}
}
}
}