我正在尝试(但失败了!)在 SwiftUI 中实现可扩展的问题和答案列表。
struct FAQ: Equatable, Identifiable {
static func ==(lhs: FAQ, rhs: FAQ) -> Bool {
return lhs.id == rhs.id
}
let id = UUID()
let question: String
let answers: [String]
var isExpanded: Bool = false
}
struct ContentView: View {
@State private (set) var faqs: [FAQ] = [
FAQ(question: "What is the fastest animal on land?", answers: ["The cheetah"]),
FAQ(question: "What colours are in a rainbox?", answers: ["Red", "Orange", "Yellow", "Blue", "Indigo", "Violet"])
]
var body: some View {
List {
ForEach(faqs) { faq in
Section(header: Text(faq.question)
.onTapGesture {
if let index = self.faqs.firstIndex(of: faq) {
self.faqs[index].isExpanded.toggle()
}
}
) {
if faq.isExpanded {
ForEach(faq.answers, id: \.self) {
Text("• " + $0).font(.body)
}
}
}
}
}
}
}
成功点击任何问题会将答案展开到视图中,但再次点击同一标题不会缩小答案,点击第二个问题也不会扩大这些答案。
通过一些明智地放置print
s ,我可以看到在点击的第一个问题上isExpanded
切换到true
,但随后不会切换回false
。
有人可以解释我做错了什么吗?