Get focused scene value

Viewed 201

I'm using macOS Monterey Beta 4 along with Xcode 13 Beta 4, and I'm trying to share information from the currently focused Scene to my apps menu (CommandGroup).

To do this, I'm using the new focusedSceneValue function. However, it doesn't seem to work.

App file:

struct ActionKey: FocusedValueKey {
    typealias Value = () -> Void
}
extension FocusedValues {
    var action: (() -> Void)? {
        get { self[ActionKey.self] }
        set { self[ActionKey.self] = newValue }
    }
}

struct TestCommands: Commands {
    @FocusedValue(\.action) var action
    
    var body: some Commands {
        CommandGroup(after: .newItem) {
            Button(action: {
                action?()
            }) {
                Text("Test menu item")
            }
            .disabled(action == nil) // This is always nil
        }
    }
}

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            TestCommands()
        }
    }
}

ContentView:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
            .focusedSceneValue(\.action) {
                print("Clicked!")
            }
    }
}

Most of the code is copied from the documentation, however the menu item is always disabled, because action is always nil (its never set by FocusedValue).

I thought focusedSceneValue would work regardless of what View is focused (as stated in the documentation).

Is there anything I am doing wrong? Any help would be awesome.

0 Answers
Related