我正在学习一些 SwiftFul Thinking 教程,我在 Nick 的代码中注意到,当他添加 EditButton() 时,他获得了“编辑”按钮的功能以及每个列表标题右侧的 V 形图标,允许折叠或展开列表。
现在 Nick 教程中的一些代码已被弃用,因此我必须更改代码才能使我的列表正常工作,但我似乎无法让展开/折叠 V 形符号浮出水面。
我的代码:
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")
}
}
在 iOS 17 之前,列表中的
Section
将获得折叠的能力,具体取决于 listStyle
和其他一些并非特别不透明的因素。
现在,如果您希望
Section
能够展开和折叠,您应该将布尔值绑定传递给该部分的初始值设定项,例如:
@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”)
}
}
}
}
有多个
Section
初始化器接受 isExpanded
参数 - 例如 this one。在文档的左侧窗格中,您会看到其他内容。