UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Adding an invisible Cmd-Key shortcut to ContentView

Forums > SwiftUI

To solve an obscure problem (don't ask!) I needed to add a Cmd-N action to my MacOS ContentView. I tried working with .onKeypress but that seemed unable to do what I needed - I couldn't specify the Cmd modifier, and it seemed unreliable. I finally realized that what I was after was the same as a button's .keyboardShortcut, but without the button. I added the button but made it invisible, as with:

Button( "New" ) {
    print( "New Action" )
    // Add more code here.
}
.opacity(0.0) // <<<<< Make it invisible!
.keyboardShortcut("n")

The button disappears to the user, and in fact if you click the invisible region, nothing happens. But the Cmd-N action continued to work. Ideally you would add the button in a region of your View where there was some open space, so that it wouldn't mess up your layout. Or you could play with making the button really small, or putting it in a ZStack on top of something else. Regardless, this allows you to add "undocumented" keyboard commands to your app. If a button can do an action, then you can add a shortcut to do that action.

Tom Coates :::/

PS. The obscure problem I had was that using a Window before a Document Group in the App body, resulted in a loss of the Cmd-N shortcut on the File->New menu. Can't say way. Just the way Swiftui decides to work. To allow Cmd-N to continue to work, I needed this workaround. The user doesn't get the prompt on File->New.

1      

why not just override the File->New menu item? you can replace the built in one (I've done that in one of my apps) with your own menu handler. Just interested to know.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.