Swiftui 将命令连接到主视图中的值

Swiftui connect command to value in main view

有人知道如何将命令连接到项目的其余部分吗?
例如:我想在内容视图中切换 AddNew 变量以使用命令显示添加新项目 sheet。

struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
             CommandGroup(after: CommandGroupPlacement.newItem) {
                Button("Add new", action: {
                    
                self.AddNew.toggle() // should toggle variable in content View

                })
            }
        }
    }
}

struct ContentView: View {
 @State var AddNew = false
    var body: some View { 

        Button(action: {
            self.AddNew.toggle()
        }) {
            Text("Show Detail")
        }.sheet(isPresented: $AddNew) {
            AddNew(dimiss: $AddNew)
        }

 }
    
}


一个解决方案可能是 @Published var 在 class 中符合 ObservableObject

您可以在 class 中切换布尔值 并从任何您想要的地方访问它(例如 @EnvironmentObject)。

像这样:

class AppModel: ObservableObject {
    
    @Published var addNew: Bool = false

}

struct SampleApp: App {

    @ObservedObject var model = AppModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(model)
        }
        .commands {
             CommandGroup(after: CommandGroupPlacement.newItem) {
                Button("Add new", action: {
                    self.model.addNew.toggle()
                })
            }
        }
    }
}

struct ContentView: View {

    @EnvironmentObject var model: AppModel

    var body: some View { 

        Button(action: {
            self.model.addNew.toggle()
        }) {
            Text("Show Detail")
        }.sheet(isPresented: $model.addNew) {
            AddNew(dimiss: $model.addNew)
        }

 }
    
}