Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically open Settings window in a macOS SwiftUI App

I have created a simple macOS-only SwiftUI app and added a Settings screen as per Apple's instructions:

import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            RootView()
        }
        Settings {
            SettingsView()
        }
    }
}

It works: the Preferences option shows up in the app menu. Now, I would also like to open this settings window programatically, e.g. when a button is clicked. Is there a way to achieve this?

I was hoping there would be a method in NSApplication, similar to the About window, but there doesn't seem to be one.

like image 807
Joshua Avatar asked Dec 18 '20 10:12

Joshua


1 Answers

By inspecting the app menu, I found this solution:

NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)

I assume that it may not pass App Review for using a private API, though, so less shady alternatives are still welcome.

Update: This has actually passed App Review, so I'm marking it as the answer for now.

like image 173
Joshua Avatar answered Sep 21 '22 08:09

Joshua