Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/105.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios SwiftUI-更改“中的属性”;onAppear“;不';出示时不要更改工作表_Ios_Swift_Swiftui - Fatal编程技术网

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的更改有关: