At the heart of SwiftUI are view modifiers, they allow us to easily add a variety of transformations to our views that often require multiple lines of code in UIKit. In a single line of code we can add shadows, change fonts, colours, scaling, offset, the list goes on.

With all this awesome functionality packed into such a lightweight piece of code you may have found yourself asking how to create your own, I found myself asking this exact question.

ViewModifier is a protocol that requires a body variable to return the opaque View type, just like a plain old SwiftUI View...turns out creating a custom view modifier couldn't be more simple!

For example, say there's a common stack of shadow modifiers you've been applying for a drop shadow, you can group them into a single view modifier like so.

struct ShadowModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .shadow(color: Color.black.opacity(0.1),
                    radius: 10, x: 0, y: 12)
            .shadow(color: Color.black.opacity(0.1),
                    radius: 1, x: 0, y: 1)
    }
}

To use it I can simply call .modifier(ShadowModifier()), it really is that simple. You can stack as many ViewModifiers as you like inside your own.

Thanks for reading ✌️