Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

swift - Swiftui connect command to value in main view

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

 }
    
}



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

 }
    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...