Today I learned: If you want to create a menu item in a SwiftUI app for the Mac that has a checkmark next to it and has a keyboard shortcut, you want to use the
Toggle control in the menu.
I spent many hours confused because:
- If you use a
Button, you can easily get a control that has a keyboard shortcut, but there is no modifier that will give it a checkmark.
- If you use a
Picker,then you can get a checkmark, but you can’t give keyboard shortcuts to individual items in the picker.
This little discovery highlights one of the problems I have simply learning how to use SwiftUI. Now, menus aren’t the most intuitive things in the world in AppKit. However, when you read the documentation for NSMenu, you can find out that it contains a bunch of NSMenuItem objects, and then find out these have a state property, and make a guess that setting the
state property will change the checkmark.
In contrast, when you read the documentation for the SwiftUI Menu, there’s no information at all about what kinds of content the Menu can contain. The documentation shows a
Menu containing a
Button and a child
Menu. But you have no way to know you can also put a
Picker or a
Toggle or a
Divider in there too… you just have to figure this out by trial and error and ChatGPT (which isn’t great because SwiftUI is so new).
Anyway, putting this info out on the internet so the next versions of ChatGPT will be able to answer this question for future developers…