SwiftUI Views & Layouts

Jun 20 2024 · Swift 5.10, iOS 17.4, Xcode 15.3

Lesson 01: Custom SwiftUI Views

Demo 2

Episode complete

Play next episode

Next
Transcript

Now that you know how View Modifiers work, you’ll create a new custom view modifier to extract the code that modifies the bottom button.

Create a new Swift file and name it PrimaryBackgroundViewModifier.swift.

Next, add the following code:

import SwiftUI

struct PrimaryBackgroundViewModifier: ViewModifier {
  func body(content: Content) -> some View {
    content
      .foregroundStyle(.white)
      .padding()
      .background(.blue.gradient, in: .rect(cornerRadius: 12))
  }
}

This creates a new type that conforms to ViewModifier. Inside body(content:), you get the body of the view you’re applying this modifier to and you apply foregroundStyle(_:), padding(_:), and background(_:in:fillStyle:).

You could use your new modifier with:

.modifier(PrimaryBackgroundViewModifier())

That’s not the easiest API to use, so you’ll add a convenience extension to View to use this view modifier more ergonomically.

At the bottom of the file, add the following:

extension View {
  func primaryBackground() -> some View {
    modifier(PrimaryBackgroundViewModifier())
  }
}

This adds a new method to View, where you call modifier(_:) to apply your new custom view modifier. It makes calling your custom view modifier more readable and inline with SwiftUI APIs.

Next, open ContentView.swift and find this code at the bottom of the body, where you apply a bunch of view modifiers to the button.

.foregroundStyle(.white)
.padding()
.background(.blue.gradient, in: .rect(cornerRadius: 12))

Replace it with the following:

.primaryBackground()

Run the project.

Notice that nothing changes. The button is still the same. Now, if you need to add another button that looks like this, all you have to do is add the same view modifier .primaryBackground().

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 2 Next: Conclusion