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

Applying groups of styles using ViewModifier

SwiftUI comes with built-in modifiers such as background() and fontWeight(), among others. It also gives you the ability to create your own custom modifiers. You can use custom modifiers to combine multiple existing modifiers into one.

In this section, we will create a custom modifier that adds rounded corners and a background to a Text view.

Getting ready

Create a new SwiftUI project named UsingViewModifiers.

How to do it…

Let’s create a view modifier and use a single line of code to apply it to a Text view. The steps are given here:

  1. Replace the current body of the ContentView view with:
    Text("Perfect")
    
  2. At the end of the ContentView.swift file, create a struct that conforms to the ViewModifier protocol, accepts a parameter of type Color, and applies styles to the view’s body:
    struct BackgroundStyle: ViewModifier {
        var bgColor: Color
        func body(content: Content) -> some View{
            content
            .frame(width:UIScreen.main.bounds.width * 0.3)
            .foregroundStyle(.black)
            .padding()
            .background(bgColor)
            .cornerRadius(20)
        }
    }
    
  3. Add a custom style to the text using the modifier() modifier:
    Text("Perfect").modifier(BackgroundStyle(bgColor:
         .blue))
    
  4. To apply styles without using a modifier, create an extension to the View protocol. The extension should be created outside the struct or Xcode will issue an error:
    extension View {
        func backgroundStyle(color: Color) -> some View{
            self.modifier(BackgroundStyle(bgColor: color))
        }
    }
    
  5. Replace the modifier on the Text view with the backgroundStyle() modifier that you just created, which will add your custom styles:
        Text("Perfect")
            .backgroundStyle(color: Color.red)
    
  6. The result should look like this:

Figure 1.15: Custom view modifier

This concludes the section on view modifiers. View modifiers promote clean coding and reduce repetition.

How it works…

A view modifier creates a new view by altering the original view to which it is applied. We create a new view modifier by creating a struct that conforms to the ViewModifier protocol and apply our styles in the implementation of the required body function. You can make the ViewModifier customizable by requiring input parameters/properties that would be used when applying styles.

In the example here, the bgColor property is used in our BackGroundStyle struct, which alters the background color of the content passed to the body function.

At the end of Step 2, we have a functioning ViewModifier but decide to make it easier to use by creating a View extension and adding in a function that calls our struct:

extension View {
    func backgroundStyle(color: Color) -> some View {
        modifier(BackgroundStyle(bgColor: color))
    }
}

We are thus able to use .backgroundStyle(color: Color) directly on our views instead of .modifier(BackgroundStyle(bgColor:Color)).

See also

Apple documentation on view modifiers: https://developer.apple.com/documentation/swiftui/viewmodifier.

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}