I try to enable/disable Command Menu buttons of the App based on the DetailView appeared or not (view appeared = button enabled).
For that I try to use @EnvironmentalObject
to receive the current condition via an ViewState
class using it to enable/disable the button:
@main
struct MyApp: App {
...
// access viewState via Environmental Object
@EnvironmentObject var viewState: ViewState
var body: some Scene {
WindowGroup {
...
}
.commands {
// changing "File" menu list
CommandGroup(after: CommandGroupPlacement.undoRedo) {
Button("Listeneintrag bearbeiten") {
// do stuff
}.disabled(!viewState.itemSelected) // <-- ERROR OCCURING
}
}
}
}
class ViewState : ObservableObject {
@Published var userSelected = false
@Published var itemSelected = false
}
详细情况 观点的出现应确定国家:
struct DetailsView: View {
...
@StateObject var viewState = ViewState()
var body: some View {
ZStack(alignment: .bottom) {
...
}
.onAppear {
viewState.userSelected = true
}
.onDisappear {
viewState.userSelected = false
}
}
错误信息是:<条码> 发现的类型观点的目的。 A View.environmentObject (_:) for ViewState may beshed as an ancestor of this view.
My approach might be completely wrong but I used it to share information from App
to the views successfully. I did not find any information on how to pass data/information from views to the (main) app struct.
Any hint?