代码之家  ›  专栏  ›  技术社区  ›  aheze But I'm Not A Wrapper Class

SwiftUI-在“onAppear”中更改属性时,不会更改工作表

  •  0
  • aheze But I'm Not A Wrapper Class  · 技术社区  · 4 年前

    options.categories 在一个 List .

    选项.类别 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 ,它起作用了。

    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"]
    }
    

    如何继续使用工作表,但在更改值时更新列表?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Leo Dabus    4 年前

    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)
                }
            }
        }
    }