我有一个按钮,当按下它时,我会出一张纸。此工作表在options.categories
中显示List
。
问题是,当我在options.categories
的{{1}}中设置ContentView
时,工作表无法反映所做的更改。仍然是一个空列表。
onAppear
结果(什么都没有显示!):
但是,如果我将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
如何继续使用工作表,但是更改值时会更新列表?
答案 0 :(得分:2)
不需要使用出现。您可以简单地初始化一个新的ViewOptions对象:
struct ContentView: View {
@State var presentingModal = false
@State var options: ViewOptions = .init(categories: ["one", "two", "three", "four"])
var body: some View {
VStack {
Text("Tap to present:")
Button("Present") {
presentingModal = true
}
.sheet(isPresented: $presentingModal) {
ModalView(options: options)
}
}
}
}