SECRET OF CSS

Create Custom View Modifiers in SwiftUI | by Ricardo Montemayor | Aug, 2022


With parameters and extension

0*RKHDKnaO7aIhakeB
Photo by Liza Pooor on Unsplash

A modifier you can apply to a View or another ViewModifier.

View modifiers essentially produce another version of the original view (A new version of the view is returned every time a modifier is applied).

That makes it possible to add multiple paddings and background colors to a single view.

Example of view modifiers chain

Let’s create our own custom ViewModifier.

We’ll create a custom ViewModifier that will make a View card-like by adding 3 existing modifiers (background, cornerRadius, and shadow).

1* qjOSFGoDBvVh1jJ9hFrng
The final product of our custom CardModifier

Create a group of Modifiers and add a new Swift file named CardModifier.swift:

You can include all your modifiers here

We need to create a struct that conforms to the ViewModifier protocol. This protocol ensures that the struct contains a function body() which allows us to use the struct as a modifier for our views.

The body() function receives Content (the view being modified) we then modify it (add corner radius, shadow, etc.) and return it.

Here’s the code for CardModifier:

To use our newly created CardModifier, add the .modifier() modifier (sorry about the redundancy) and initialize the struct inside.

Simple view example
1*Ap6nMJ8uwdsPy3kT5rz2EQ

What the .modifier() does is apply all the modifiers defined in our CardModifier and return the new view. So it’s as if we were adding them right there but without typing the code each time!

1*TFfhGi8uZcOhrYbPOPkP8Q

Use custom view modifiers when you are going to be using the same set of modifiers in different views.

We have all the flexibility in the world. We can build more complex views and apply the CardModifier all the same.

Complex view example

We can make our custom view modifiers more flexible by adding parameters.

Add a backgroundColor property to our existing CardModifier. Make it white by default (if no background color was specified).

CardModifier with custom background color

We can now optionally set a custom background color for our CardModifier.

1*3aAn uf2qkOr9o kmp6HGA

Wouldn’t it be nice to use autocompletion for your custom view modifiers?

Let’s do that.

Create a group for Extensions and add a new Swift file named View+Extensions.swift

1*UrhDd7cYtDSJZWzuDW99aA

We are going to create a modifier .card() with an optional background color as a parameter.

Add the following code:

We can now use .card() to use our CardModifier.



News Credit

%d bloggers like this: