【发布时间】:2020-04-27 18:02:00
【问题描述】:
根据我的理解,我编写了以下代码,用于展开/折叠列表中的一个部分。
struct WORKING_CollapsableListView: View {
@State var sectionExpansionStates = [true, true, true]
var body: some View {
VStack {
List {
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[0])) {
if self.sectionExpansionStates[0] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[0] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[0] ? 10 : 10)
}
}
}
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[1])) {
if self.sectionExpansionStates[1] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[1] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[1] ? 10 : 10)
}
}
}
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[2])) {
if self.sectionExpansionStates[2] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[2] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[2] ? 10 : 10)
}
}
}
}
}
}
}
struct CollapsableSectionHeader: View {
@Binding var expansionState: Bool
var body: some View {
Button(action: {
self.expansionState.toggle()
}) {
Text("HEADER: \(expansionState ? "Expanded" : "Collapsed")")
.bold()
}
}
}
这按预期工作。但是,以下代码不起作用。我所做的只是用ForEach 替换了多个部分。这段代码的行为应该是相同的,但是当我点击部分标题时没有任何反应。我错过了什么?好像绑定不起作用。
struct NOT_WORKING_CollapsableListView: View {
@State var sectionExpansionStates = [true, true, true]
var body: some View {
VStack {
List {
ForEach(0 ..< 3) { section in
Section(header: CollapsableSectionHeader(expansionState: self.$sectionExpansionStates[section])) {
if self.sectionExpansionStates[section] {
ForEach(0..<10) { item in
Text("\(item) is \(self.sectionExpansionStates[section] ? "Expanded" : "Collapsed")")
.frame(height: self.sectionExpansionStates[section] ? 10 : 10)
}
}
}
}
}
}
}
}
【问题讨论】: