Skip to content

Adding Settings Panel to macOS App with SwiftUI

Published: at 03:22 PM

In traditional AppKit development, adding a common “Preferences” settings panel to a macOS app requires several steps, including adding a MenuItem and creating a new Window, often requiring navigation between code and Storyboard.

However, when using SwiftUI for development, I discovered that adding a settings panel to a macOS app is incredibly simple and can be done in just 2 steps:

1. Create a SettingView

Similar to developing a regular view, create a view specifically for settings. Here, I added a TabView for categorization:

struct SettingView: View {
    var body: some View {
        TabView {
            Text("General")
                .tabItem {
                    Label("General", systemImage: "gear")
                }
            Text("User")
                .tabItem {
                    Label("User", systemImage: "person")
                }
        }
        .frame(width: 400, height: 200)
    }
}

2. Add Settings in @main

@main
struct SOSApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }

#if os(macOS)
        Settings {
            SettingView()
        }
#endif
    }
}

The #if os(macOS) conditional statement is added here because my app supports both iOS and macOS. Without this distinction, the iOS target will not compile.

With these two steps completed, after building the app, you will see that your app has added a “Preferences” menu item. Apple even handles the localization of the menu name for you and sets the default keyboard shortcut.