【发布时间】:2020-10-24 23:52:36
【问题描述】:
我有一个按钮,当按下它时,我会展示一张纸。此工作表在 List 中显示 options.categories。
问题是当我在ContentView 的onAppear 中设置options.categories 时,工作表没有反映更改。它仍然是一个空列表。
struct ViewOptions {
public var categories = [String]()
}
struct ContentView: View {
@State var presentingModal = false
@State var options = ViewOptions()
var body: some View {
VStack {
Text("Tap to present:")
Button("Present") { presentingModal = true } /// set presentingModal to true, to present the sheet
.sheet(isPresented: $presentingModal) {
ModalView(options: options)
}
}
.onAppear {
options.categories = ["one", "two", "three", "four"]
}
}
}
struct ModalView: View {
var options: ViewOptions
var body: some View {
List { /// display options.categories in a List
ForEach(options.categories, id: \.self) { word in
Text(word)
}
}
}
}
结果(什么都不显示!):
但如果我注释掉 .sheet 并将 ModalView 嵌入到 ContentView 中,它就可以工作。
VStack {
Text("Tap to present:")
Button("Present") { presentingModal = true }
// .sheet(isPresented: $presentingModal) { /// get rid of the sheet
ModalView(options: options)
// }
}
.onAppear {
options.categories = ["one", "two", "three", "four"]
}
如何才能继续使用工作表,但在更改值时更新列表?
【问题讨论】:
-
这可能与 iOS 14 的变化有关:iOS14 introducing errors with @State bindings