Separating presentation from content with ViewBuilder
Apple defines ViewBuilder
as "a custom parameter attribute that constructs views from closures". ViewBuilder
can be used to create custom views that can be used across an application with minimal or no code duplication. In this recipe, we will create a SwiftUI view, BlueCircle
, that applies a blue circle to the right of its content.
Getting ready
Let's start by creating a new SwiftUI project called UsingViewBuilder
.
How to do it…
We'll create our ViewBuilder
in a separate swift file and then apply it to items that we'll create in the ContentView.swift
file. The steps are given here:
- With our
UsingViewBuilder
app opened, let's create a new SwiftUI file by going to File | New | File. - Select SwiftUI view from the menu and click Next.
- Name the file
BlueCircle
and click Create. - Delete the
BlueCircle_Previews
struct from the file. - Add the
BlueCircle
ViewModifier...