3 ways of styling SwiftUI views

Philip Niedertscheider
Level Up Coding
Published in
4 min readMay 24, 2021

--

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:

  1. Initializer-based configuration
  2. Method chaining using return-self
  3. 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.

The property wrapper you will find in chapter 3 “Styles in Environment”

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 is CMD(⌘) + left-click on the type name, and select the action.

Xcode can automatically generate memberwise initializers

Using a custom initializer allows us to add default values directly there without changing the let of the parameters to var ones:

--

--

Changing the status quo of iOS & macOS development | Self-Taught | Co-Founder/CTO @techprimate | Follow me on Twitter @philprimes for updates 🚀