首页 > 解决方案 > 如何在 Swiftui 中更改不同文件中的变量值

问题描述

我在内容视图中设置了一个变量@State var shouldShowModal = false,我想在按下按钮后更改它shouldShowModal = false。我一直在范围内找不到“shouldShowModal”。

标签: variablesswiftui

解决方案


这是一个工作示例,通过@Bindings 传递值。阅读更多关于@Binding 这里,或官方文档

这意味着您现在可以shouldShowModal = false使用绑定,这也将更新包含@State.

struct ContentView: View {
    
    @State private var shouldShowModal = false
    
    var body: some View {
        VStack {
            Text("Hello world!")
                .sheet(isPresented: $shouldShowModal) {
                    Text("Modal")
                }
            
            OtherView(shouldShowModal: $shouldShowModal)
        }
    }
}


struct OtherView: View {
    
    @Binding var shouldShowModal: Bool
    
    var body: some View {
        VStack {
            Text("Should show modal: \(shouldShowModal ? "yes" : "no")")
            
            Toggle("Toggle modal", isOn: $shouldShowModal)
        }
    }
}

推荐阅读