Separating presentation from content with ViewBuilder
ViewBuilder
is a custom parameter attribute that constructs views from closures. ViewBuilder
can be used to create custom views that can be used across the application with minimal or no code duplication. We will create a SwiftUI view, BlueCircle.swift
, for declaring the ViewBuilder
and implement the custom ViewBuilder
. The ContentView.swift
file will be used to implement the custom view.
Getting ready
Create a new SwiftUI project named ViewBuildersApp
.
How to do it…
- Open the ViewBuildersApp and add a new SwiftUI view to the project from the menu: File | New | File.
- Select the SwiftUI view from the menu.
- Click Next.
- Name the file
BlueCircle
and click Create. - Delete the
BlueCircle_Previews
: struct from the file (delete all five lines of code). - Add
BlueCircle ViewModifier
to the file:struct BlueCircle<Content: View>: View { let content: Content ...