I have an app which uses SwiftUI and Mac Catalyst. When running on a Mac I want to provide a preferences menu entry with the usual keyboard shortcut Command + ,. An implementation via the Settings bundle is out of question since my preferences are too complex for this.
Here is a reduced example of my implementation:
import SwiftUI
@main
struct PreferencesMenuTestApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
override func buildMenu(with builder: UIMenuBuilder) {
let preferencesCommand = UIKeyCommand(title: "Preferences…",
action: #selector(showPreferences),
input: ",",
modifierFlags: .command)
// let preferencesCommand = UIAction(title: "Preferences…") { action in
// debugPrint("show preferences")
// }
let menu = UIMenu(title: "Preferences…",
options: .displayInline,
children: [preferencesCommand])
builder.insertSibling(menu, afterMenu: .about)
}
@objc
func showPreferences() {
debugPrint("show preferences")
}
}
The problem is that the menu entry is disabled. Obviously the provided selector is not recognised. When I mark the AppDelegate
with @main
, then the menu entry is enabled. Of course then the app's window is empty.
When I switch to the UIAction
implementation (the out commented code) it works fine. But since one cannot provide a keyboard shortcut for UIAction
s this is not a good solution.
What am I missing? How would one implement a preferences menu entry that actually works?