Build a ViewModifier in SwiftUI

Moussa Hellal
3 min readMay 20, 2023

ViewModifiers make it simple to alter the look and behavior of views, which helps your SwiftUI code to be cleaner and easier to maintain.

You might experienced in SwiftUI the power of some Built-in ViewModifiers such as

.padding(), .foregroundColor(), .font(), .background(),

.rotationEffec(),.clipShape(), .overlay()

In this post, we’ll explore the realm of view modifiers, learn how to make and use them, and explore their capabilities.

By the way, if you want to just copy the end result and understand for yourself, just scroll to the bottom of the article and you will get both files.

Let’s start with the simplest possible SwiftUI View: Which is an Image

As you can we have used the built-in modifiers .resisable()and.aspectRatio()

In our example here we want to add some shadow, DragGesture, and a simple animation.

Now we will add few ViewModifiers for our shadow, DragGesture.

Now comes into place our Custom ViewModifier that will handle and encapsulate all of this and our code can be more modular and cleaner.

Let’s create a new file and name it DraggableModifier

Our DraggableModifier struct here is conforming to the SwiftUI Protocol ViewModifier.

As observed here, we have extracted and put in a separate file every modifier that was used in our ContentView and even the state that keeps track of our DragGesture.

We are now ready to accept content as a parameter to which these modifiers will be applied to.

Now we can get back to our main ContentView and simply remove all of our VStack modifiers and the state for offset.
and Add our custom one through .modifier(DraggableModifier):

Way Cleaner. Easier to Understand. Precise and to the point.

That’s it as Simple as that; You can quickly build sophisticated UI by encapsulating view transformations into reusable modifiers.

Final code

Our Main View that we have used the image and the modifier In:

Our Custom Modifier that we have encapsulated all our used modifiers in:

I appreciate you choosing to spend some of your day with me. I hope that my piece was informative and helpful to you.

Farewell, keep growing and learning. See you in the next one. ✌️

Make sure to follow me on Twitter to keep receiving the newest articles:

https://twitter.com/codeWithMoses

--

--