I'm going through some SwiftFul Thinking tutorials and I noticed in Nick's code when he adds EditButton() he gets the functionality of the Edit button and a chevron to the right of each List title that allows the list to be collapsed or expanded.
Now a few bits of code in Nick's tutorial have been deprecated, so I had to change the code to make my List work, but I can't seem to get that expand/collapse chevron to surface.
My Code:
import SwiftUI
struct ListBootcamp: View {
@State var fruits: [String] = [
"apple", "orange", "banana", "peach"
]
@State var veggies: [String] = [
"tomato", "potato", "carrot"
]
var body: some View {
NavigationView {
List {
Section(header:
HStack {
Text("Fruits")
Image(systemName: "flame.fill")
}
.font(.headline)
.foregroundStyle(Color.orange)
) {
ForEach(fruits, id: \.self) { fruit in
Text(fruit.capitalized)
.font(.caption)
.foregroundStyle(Color.white)
.padding(.vertical)
}
.onDelete(perform: delete)
.onMove(perform: move)
.listRowBackground(Color.pink)
}
Section(header: Text("Veggies").foregroundStyle(Color.blue)) {
ForEach(veggies, id: \.self) { veggies in
Text(veggies.capitalized)
}
}
}
.listStyle(DefaultListStyle())
.navigationTitle("Grocery List")
// Code in question here
.toolbar {
ToolbarItem(placement: .topBarLeading) {
EditButton()
}
ToolbarItem(placement: .topBarTrailing) {
addButton
}
}
}
.tint(.green)
}
var addButton: some View {
Button("Add") {
add()
}
}
func delete(indexSet: IndexSet) {
fruits.remove(atOffsets: indexSet)
}
func move(indices: IndexSet, newOffset: Int) {
fruits.move(fromOffsets: indices, toOffset: newOffset)
}
func add() {
fruits.append("coconut")
}
}
Prior to iOS 17, Section
s in lists would gain the ability to collapse depending on the listStyle
and a few other factors that weren’t particularly opaque.
Now, if you want a Section
to be able to expand and collapse, you should pass a Boolean binding to the Section’s initializer, e.g.:
@State private isExpanded = true
var body: some View {
List {
Section(isExpanded: $isExpanded) {
// your list rows go here
} header: {
HStack {
Text(“Fruits”)
Image(systemName: “flame.fill”)
}
}
}
}
There are several Section
initializers that accept an isExpanded
argument - for example this one. In the documentation’s left hand pane you’ll see others.