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.
Add a preferences window to your macOS app in minutes Just pass in some view controllers and this package will take…
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.
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.