Book Image

SwiftUI Cookbook - Third Edition

By : Juan C. Catalan
5 (1)
Book Image

SwiftUI Cookbook - Third Edition

5 (1)
By: Juan C. Catalan

Overview of this book

SwiftUI is the modern way to build user interfaces for iOS, macOS, and watchOS. It provides a declarative and intuitive way to create beautiful and interactive user interfaces. The new edition of this comprehensive cookbook includes a fully updated repository for SwiftUI 5, iOS 17, Xcode 15, and Swift 5.9. With this arsenal, it teaches you everything you need to know to build beautiful and interactive user interfaces with SwiftUI 5, from the basics to advanced topics like custom modifiers, animations, and state management. In this new edition, you will dive into the world of creating powerful data visualizations with a new chapter on Swift Charts and how to seamlessly integrate charts into your SwiftUI apps. Further, you will be able to unleash your creativity with advanced controls, including multi-column tables and two-dimensional layouts. You can explore new modifiers for text, images, and shapes that give you more control over the appearance of your views. You will learn how to develop apps for multiple platforms, including iOS, macOS, watchOS, and more. With expert insights, real-world examples, and a recipe-based approach, you’ll be equipped to build remarkable SwiftUI apps that stand out in today’s competitive market.
Table of Contents (20 chapters)
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.