@FocusedValue from .focusedSceneValue from the Scene Commands

Hi,

In iPadOS can we use a .focusedSceneValue, defined from a command/Button inside a Scene, from inside the .command modifier attached to the scene?

Like this:

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

struct NavigationCommands: Commands {
    @FocusedValue(\.filterAction) var filterAction

    var body: some Commands {

        CommandMenu("Navigate") {
            Button("Test focusedSceneValue") {
                filterAction?()
            }
            .keyboardShortcut("5")
        }
    }
}

struct ContentView: View {
    @FocusState var isFiltering: Bool
    @State private var focusField: String = "***** field *****"

    var body: some View {

        TextField("***** focus", text: $focusField)
            .focused($isFiltering)
            .focusedSceneValue(\.filterAction) {
                print("test successful")
                isFiltering = true
            }
    }

This code is almost the same from the sample code from the documentation, however I can only retrieved nil values from the @FocusedValue and not the defined value.

Thanks.

Answered by colaco in 685975022

This bug seems now to be fixed.

It seems that is a bug.

As described in the Bug Report that I sent to Apple (FB9163579):

As described in the docs .focusedSceneValue modifies this view by injecting a value that you provide for use by other views whose state depends on the focused scene. One of the aims is to make available to the Scene commands some way to change the Scene view states. However it doesn't work. > These value are always nil, as if the view that is modified by .focusedSceneValue isn't in a Scene with focus. The same happens if another view of the Scene tries to retrieve the value with @FocusedValue. In the code sample that I've attached a Button will execute the closure that is the value being shared. But if the Button is pressed with a keyboard shortcut @FocusedValue will be nil.

Sample project here.

Accepted Answer

This bug seems now to be fixed.

If you add this? :

extension FocusedValues {
    // MARK: - Actions
    var filterAction: (() -> Void)? {
        get { self[FilterActionKey.self] }
        set { self[FilterActionKey.self] = newValue }
    }

    private struct FilterActionKey: FocusedValueKey {
        typealias Value = () -> Void
    }
}

MacOS 12 - Xcode 13 beta 5

My macOS application that used focusedValues that was working correctly on Big Sur, is not working on Monterrey. I am using focused values for macOS menu like passing currently active document viewModel, and the focusedValues when retrived via @FocusedValue are always nil.

This breaks absolutelly the Main Menu commands on Monterrey.

@FocusedValue from .focusedSceneValue from the Scene Commands
 
 
Q