3 ways of styling SwiftUI views
Styling a view is the most important part of building beautiful user interfaces. When it comes to the actual code syntax, we want reusable, customizable and clean solutions in our code.
This article will show you these 3 ways of styling a SwiftUI.View
:
- Initializer-based configuration
- Method chaining using return-self
- Styles in the Environment
As a general rule of thumb, any approach is viable. In the end, it comes down to your general code-style guidelines and personal preferences.
1. Initializer-based configuration
This is one is straight forward and can be visualized with an example rather quickly:
This view takes two parameters backgroundColor
and textColor
, which are both required when instantiating the struct. They are also both constant let
values, as the view most likely isn’t going to be mutated (at this point).
Conveniently Swift automatically synthesizes the (internal) required initializer, but they can also manually be defined be us:
Quick Tip:
Xcode also provides us with a built-in function to generate memberwise initializers. All you have to do isCMD(⌘) + left-click
on the type name, and select the action.
Using a custom initializer allows us to add default values directly there without changing the let
of the parameters to var
ones: