I have a SwiftUI list with expandable/collapsable rows. I am attempting to add a Section with a header title at the top of my list. The code prior to adding the section is as follows:
var body: some View {
List(parentArray, id: .self, children: .child) { item in
ResultsRowView(circle: item.circle.lowercased(), person: item.person, tally: item.tally)
}.listStyle(GroupedListStyle())
}
When I try to add a Section, I am getting funky results. For example, I have tried this:
var body: some View {
List(parentArray, id: .self, children: .child) { item in
Section(header: Text("HeaderTitle")) {
ResultsRowView(circle: item.circle.lowercased(), person: item. person, tally: item.tally)
}
}.listStyle(GroupedListStyle())
}
But that only adds a "HeaderTitle" text element to each of the rows in my list.
Then I tried this:
var body: some View {
Section(header: Text("HeaderTitle")) {
List(parentArray, id: .self, children: .child) { item in
ResultsRowView(circle: item.circle.lowercased(), person: item.person, tally: item.tally)
}.listStyle(GroupedListStyle())
}
}
But the result of this is that the list disappears entirely and is replaced by the text "HeaderTitle" set in the middle of the screen.
The outcome I am looking for, as you might image, is for a section with a header at the top of my list. Any ideas?
EDIT: my own data would be too cumbersome to include for others to try out. But below is code that follows the same structure as my own, pulled from Paul Hudson's Hacking With Swift website:
import SwiftUI
struct ContentView: View {
let items: [Bookmark] = [.example1, .example2, .example3]
var body: some View {
List(items, children: .items) { row in
Image(systemName: row.icon)
Text(row.name)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Bookmark: Identifiable {
let id = UUID()
let name: String
let icon: String
var items: [Bookmark]?
// some example websites
static let apple = Bookmark(name: "Apple", icon: "1.circle")
static let bbc = Bookmark(name: "BBC", icon: "square.and.pencil")
static let swift = Bookmark(name: "Swift", icon: "bolt.fill")
static let twitter = Bookmark(name: "Twitter", icon: "mic")
// some example groups
static let example1 = Bookmark(name: "Favorites", icon: "star", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
static let example2 = Bookmark(name: "Recent", icon: "timer", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
static let example3 = Bookmark(name: "Recommended", icon: "hand.thumbsup", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
}