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:
You can use it like this:
The result is:
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:
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:
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…
Passionate iOS developer for almost six years. SwiftUI/Combine early adopter. Author of SwiftUI NavigationStack https://bit.ly/2H6YjQS