Ios SwiftUI-更改“中的属性”;onAppear“;不';出示时不要更改工作表
我有一个按钮,当它被按下时,我会出示一张纸。此工作表在Ios SwiftUI-更改“中的属性”;onAppear“;不';出示时不要更改工作表,ios,swift,swiftui,Ios,Swift,Swiftui,我有一个按钮,当它被按下时,我会出示一张纸。此工作表在列表中显示选项.类别 问题是,当我在ContentView的onAppear中设置选项.categories时,工作表不会反映更改。它仍然是一个空列表 struct ViewOptions { public var categories = [String]() } struct ContentView: View { @State var presentingModal = false @State var opti
列表中显示选项.类别
问题是,当我在ContentView
的onAppear
中设置选项.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"]
}
如何继续使用工作表,但在更改值时更新列表?无需在出现时使用。您只需初始化一个新的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)
}
}
}
}
这可能与iOS 14的更改有关: