Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SwiftUI Cookbook - Third Edition

You're reading from  SwiftUI Cookbook - Third Edition

Product type Book
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Pages 798 pages
Edition 3rd Edition
Languages
Concepts
Author (1):
Juan C. Catalan Juan C. Catalan
Profile icon Juan C. Catalan

Table of Contents (20) Chapters

Preface 1. Using the Basic SwiftUI Views and Controls 2. Displaying Scrollable Content with Lists and Scroll Views 3. Exploring Advanced Components 4. Viewing while Building with SwiftUI Preview in Xcode 15 5. Creating New Components and Grouping Views with Container Views 6. Presenting Views Modally 7. Navigation Containers 8. Drawing with SwiftUI 9. Animating with SwiftUI 10. Driving SwiftUI with Data 11. Driving SwiftUI with Combine 12. SwiftUI Concurrency with async await 13. Handling Authentication and Firebase with SwiftUI 14. Persistence in SwiftUI with Core Data and SwiftData 15. Data Visualization with Swift Charts 16. Creating Multiplatform Apps with SwiftUI 17. SwiftUI Tips and Tricks 18. Other Books You May Enjoy
19. Index

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 custom 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:

  1. With our UsingViewBuilder app opened, let’s create a new SwiftUI file by going to File | New | File.
  2. Select SwiftUI view from the menu and click Next.
  3. Name the file BlueCircle and click Create.
  4. Delete the #Preview macro from the file.
  5. Modify the existing struct with the BlueCircle ViewModifier:
    struct BlueCircle<Content: View>: View {
        let content: Content
        init(@ViewBuilder content: () -> Content) {
            self.content = content()
        }
        var body: some View {
                HStack {
                   content
                    Spacer()
                    Circle()
                        .fill(Color.blue)
                        .frame(width:20, height:30)
                }
                .padding()
        }
    }
    
  6. Open the ContentView.swift file and try out the BlueCircle ViewBuilder:
        var body: some View {
            VStack {
                BlueCircle {
                    Text("some text here")
                    Rectangle()
                    .fill(Color.red)
                    .frame(width: 40, height: 40)
                }
                BlueCircle {
                    Text("Another example")
                }
            }
        }
    
  7. The resulting preview should look like this:

Figure 1.16: ViewBuilder result preview

How it works…

We use the ViewBuilder struct to create a view template that can be used anywhere in the project without duplicating code. The ViewBuilder struct must contain a body property since it extends the View protocol.

Within the body property/view, we update the content property with the components we want to use in our custom view. In this case, we use a BlueCircle. Notice the location of the content property. This determines the location where the view passed to our ViewBuilder will be placed.

See also

Apple documentation on ViewBuilder: https://developer.apple.com/documentation/swiftui/viewbuilder.

You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023 Publisher: Packt ISBN-13: 9781805121732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}