Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Does someone know how to connect commands to the rest of the project?
For example: I want to toggle the AddNew variable in the content view to show the add new item sheet by using the command.

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

 }
    
}



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

A solution could be to have a @Published var in a class conforming to ObservableObject.

You would toggle the boolean in the class and access it from wherever you want (as an @EnvironmentObject for example).

Like this:

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

 }
    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...