user16923830
user16923830

Reputation:

focusedSceneValue fixed by searchable

I'm getting this odd issue where focusedSceneValue doesn't work on macOS Monterey Beta 6, but adding searchable to one of the views fixes it.

Here's how to reproduce:

First paste this code into ContentView:

struct ContentView: View {
    @State var search = ""
    
    var body: some View {
        NavigationView {
            Text("First")
                .focusedSceneValue(\.customAction) {
                    print("Pressed!")
                }
            Text("Second")
                .searchable(text: $search) // Comment this line and focusedSceneValue breaks
        }
    }
}

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

And then paste this into your app file:

struct CustomCommands: Commands {
    @FocusedValue(\.customAction) var action
    
    var body: some Commands {
        CommandGroup(before: .newItem) {
            Button(action: {
                action?()
            }) {
                Text("Press me")
            }
            .disabled(action == nil)
        }
    }
}

And add this into the body of your Scene:

.commands {
    CustomCommands()
}

This just adds a menu item to File, and the menu item is enabled only if a variable named action is not nil.

action is supposed to be assigned in the focusedSceneValue line in ContentView. This should always happen, as long as the ContentView is visible.

This code only works if I add the searchable modifier to one of the views however. If I don't add it, then the menu item is permanently disabled.

Is anybody else able to reproduce this?

Upvotes: 2

Views: 528

Answers (2)

marcprux
marcprux

Reputation: 10355

This appears to be fixed in Monterey 12.1 (21C52), so the .searchable workaround should no longer be needed.

Upvotes: 0

Omar
Omar

Reputation: 156

There seems to be a bug with implementing focusedSceneValue (SwiftUI and focusedSceneValue on macOS, what am I doing wrong?).

From what you have shared, it seems that the .searchable modifier provides a focus for a view in the scene so that the focusedSceneValue is updated when the focus changes.

In the focusedSceneValue documentation, it recommends using this method "for values that must be visible regardless of where focus is located in the active scene." Implicitly, it could be that focusedSceneValue only works when an active scene has focus somewhere within.

Upvotes: 1

Related Questions