【问题标题】:SwiftUI - changing property in "onAppear" doesn't change sheet when presented [duplicate]SwiftUI - 更改“onAppear”中的属性在呈现时不会更改工作表[重复]
【发布时间】:2020-10-24 23:52:36
【问题描述】:

我有一个按钮,当按下它时,我会展示一张纸。此工作表在 List 中显示 options.categories

问题是当我在ContentViewonAppear 中设置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 swift swiftui


【解决方案1】:

无需在出现时使用。您可以简单地初始化一个新的 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)
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多