SwiftUI tips and tricks

How to create a custom view that accepts optional content through ViewBuilder closures

ViewBuilder closures are one of the most important and widely used function builders in SwiftUI. They let you create a view out of a closure containing multiple child views.

For example, we might create a view called RedPage which is a reusable full screen view with a red background, a main content and a header:

ViewBuilder closure.

You can use it like this:

ViewBuilder closure usage.

The result is:

ViewBuilder closure example.

Now, what if I wanted the header in the red page to be optional? I want my custom RedPage to be called like in the example above, or just like this:

SwiftUI tips and tricks

Leveraging the buildIf and buildEither functions to improve the readability of your code

When it comes to conditionally applying a modifier to a view in SwiftUI there are a couple of approaches, depending on your needs.

Well, if you know SwiftUI you are very likely already familiar with this kind of things. If you need to apply different instances of a specific modifier to a view, this is by far the most common and SwiftUI compliant way to do that. Let’s see a very simple example:

SwiftUI ternary conditional operator

foregroundColor modifier is Color.red or Color.yellow based on the value of condition. Pretty straightforward.

But what if I liked conditionally including/excluding a modifier…

Matteo Puccinelli

Passionate iOS developer for almost six years. SwiftUI/Combine early adopter. Author of SwiftUI NavigationStack https://bit.ly/2H6YjQS

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