NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Learn more...

Provide the current document to menu commands in a SwiftUI app

Starting from macOS 12 and iPadOS 15 we have focusedSceneValue() modifier in SwiftUI. It works similar to focusedValue() but does not require the wrapped view to be focused. Instead, it emits values based on the scene that is focused.

This new focusedSceneValue() modifier makes it possible for us to pass data from the focused scene to the commands section of our app. Let us consider a simple document based app that uses DocumentGroup(newDocument:editor:) API. In its commands section we would like to mutate the document and enable or disable some commands based on the document state.

For this example we will create a command that uppercases the document's text, but is only enabled if the text is not already all uppercased.

First, we declare an extension on FocusedValues.

extension FocusedValues {
    struct DocumentFocusedValues: FocusedValueKey {
        typealias Value = Binding<ExampleShortcutsDocument>
    }

    var document: Binding<ExampleShortcutsDocument>? {
        get {
            self[DocumentFocusedValues.self]
        }
        set {
            self[DocumentFocusedValues.self] = newValue
        }
    }
}

Note that we are using a binding to the document rather than just the raw document. We do it because the document is a struct, and for the commands menu to mutate it, it needs to be a binding.

Luckily, DocumentGroup(newDocument:) already provides us with a binding to our document.

DocumentGroup(newDocument: ExampleShortcutsDocument()) { file in
    ContentView(document: file.$document)
        .focusedSceneValue(\.document, file.$document)
}

Now we need to make use of the @FocusedBinding property wrapper.

struct UppercasedText: View {
    @FocusedBinding(\.document) var document
   
    var body: some View {
        Button {
            guard let text = document?.text else {
                return
            }
            document?.text = text.uppercased()
        } label: {
            Text("Uppercased")
        }
        .disabled(
            document == nil ||
                document?.text == document?.text.uppercased()
        )
        .keyboardShortcut("u", modifiers: [.command, .shift])
  }
}

It's best to separate our command into its own view.

Then we can add our new command to the app inside the main App struct.

@main
struct ExampleShortcutsApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: ExampleShortcutsDocument()) { file in
            ContentView(document: file.$document)
                .focusedSceneValue(\.document, file.$document)
        }
        .commands {
            CommandMenu("Document") {
                UppercasedText()
            }
        }
    }
}
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

100+ tips to take your Swift code to the next level

Swift Gems

100+ tips to take your Swift code to the next level

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift