I'm just migrating some ObservedObjects to Observable and ran into this problem with a Commands menu with a FocusedObject dependency. I want some entries in the menu to be enabled and to act on state from the Observable object.
What finally worked for me (so far) is using a FocusedValues extension. I couldn't get this to work without the key path API, despite what the documentation says, and there doesn't appear to be a single example on the Internet.
struct MyFocusedObservableStateValue: FocusedValueKey {
typealias Value = MyObservableStateType
}
extension FocusedValues {
var myObservableState: MyFocusedObservableStateValue.Value? {
get { self[MyFocusedObservableStateValue.self] }
set { self[MyFocusedObservableStateValue.self] = newValue }
}
}
struct ItemActionsCommandMenu: Commands {
@FocusedValue(\.myObservableState) var myObservableState
var body: some Commands {
CommandMenu("Menu Name") {
// use myObservableState as needed (Note: It's optional)
Button("Action") {
}
.disabled(...)
}
}
}
Elsewhere in App:
myContentView
.focusedSceneValue(\.myObservableState, myObservableState)
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: