How to create a preferences window in Big Sur with SwiftUI

Image for post
Image for post
SwiftUI preferences window

In this tutorial we will be writing a preferences windows for a native Big Sur macOS app written with SwftUI.

We will be using the amazing Preferences library by Sindre Sorhus.

After adding the library to our Xcode project, the first to do is create the a SwiftUI view.

Import the Preferences library and replace the Hello World text with a Preferences.Container and inside it a Preferences.Section, because it is a SwiftUI you cand add any supported view like Buttons, Pickers, Sliders…

The code below should show you something like the image below.

Image for post
Image for post

Right now the preferences aren´t stored anywere so every time the view is destroyed, all user seleccions are lost. To solve this problem, change the @State modifier for @AppStore, this way the values are automatically saved and restored by the system.

To add a little bit of variation, create another view for more user actions, like database manipulation.

Now that all the SwiftUI views are created, create an extension of Preferences.PaneIdentifier.

The next step is the creation of two PaneHostingController, as you can see we can user SF Symbols for the icon that will be show in the toolbar of the window.

The last step is to overwrite the command that opens the Setting view is macOS with a Button that created a PrefeferencesWindowController with the two PaneHostingControllers.

Congratulations! Now you have a totally responsive and native preferences windows, following the big sur desing style and writed with SwiftUI.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store