Understanding SwiftUI ViewModifiers: A Comprehensive Guide

Santosh Botre
4 min readOct 4, 2023

--

Power of ViewModifers

Creating user interfaces for iOS simpler and more flexible with SwiftUI 😎.

A notable aspect of this framework is ViewModifiers.

We will take an in-depth look at SwiftUI ViewModifiers, their implementation, and the advantages and disadvantages of utilizing custom ViewModifiers in real projects.

If you have tried using SwiftUI, I’m sure you’ve come across functions such as .padding(), .font(_ font:), .foregroundColor(_ color:), .imageScale(_ scale:) and many more…

NOTE: There is a large set of functions called ViewModifiers that can be applied to a View.

Each app features a collection of buttons that possess a consistent appearance i.e., title font, background color, font weight, title color etc.

Let’s see an example,

An e-commerce application will include buttons for View Details, checkout, and more such actionable buttons.

E-com common actionable buttons

NOTE: Every button code will be in a different view. However, for simplicity, I have put it in the same view.

Your inner soul like,

Your inner soul 😊

A seasoned iOS developer would suggest creating a function to return the Button.

Pass parameters for different titles and action closures.

Try to return the Button and you will end up seeing an Error.

Reference to generic type 'Button' requires 
arguments in <…>. Insert '<<#Label: View#>>'

The workaround is to return any View. Still, we see an error, then wrap it in any View. and while using it in View again wrap it in any View.

Finally, it worked... The code might look messy again, as shown below.

any View

I know, you are a smart developer and might be aware of the opaque return type ‘some’ since Swift 5.1.

some View

Wow…. Looks great, but there are some clouds in the sky. As we continue with the project, we may have to make the function static to use it in multiple places.

Wouldn’t it be great if we could create a custom ViewModifier that groups all built-in view modifiers and applies them to a view?

Certainly, however, before using it, let’s try and understand ViewModifer.

1. Introduction to ViewModifier

In SwiftUI, a ViewModifier is a protocol that defines a transformation you can apply to a view.

The ViewModifier protocol has one required method:

protocol ViewModifier {
associatedtype Body: View
func body(content: Content) -> Self.Body
}

Below is what it has.

  • Body: This is an associated type that represents the modified view. It conforms to the View protocol, which means it can be used in SwiftUI view hierarchies.
  • body(content:): This method takes an input view (Content) and returns a modified view (Self.Body).

Within this method, we define the modifications we want to apply to the input view and return the modified version.

2. Creating Custom ViewModifiers

Start by creating a basic theme button for our Ecom use case. 🔍💡💻💪

struct CustomEComThemeButton: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title3)
.fontWeight(.heavy)
.frame(height: 50)
.frame(maxWidth: .infinity)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}

3. Applying Custom ViewModifiers

You can apply the custom modifier to any view within your SwiftUI hierarchy:

Button(action: {}, label: {
Text("View Details")
}).modifier(CustomEComThemeButton())

Done…….

https://gifer.com/en/gifs/happy
Complete Code

However, we all might feel, that using .modifer() every time to apply our custom ViewModifier doesn't feel like home.

Pro Tip — Can we leverage the extension feature on View?

// Extension
extension View {
func customEComThemeButton() -> some View {
return self
.modifier(CustomEComThemeButton())
}
}

// Usage
Button(action: {}, label: {
Text("View Details")
}).customEComThemeButton()

Now, we can use our Custom ViewModifer just like an in-built ViewModifer.

4. Why we should us Custom ViewModifiers

  • Reusability: Custom ViewModifiers promote the reusability of view styling and behaviour across different parts of your application.
  • Readability: Encapsulating complex view logic into a single modifier improves code readability and maintainability.
  • Composability: ViewModifiers can be combined and composed to create more complex styles and behaviours.
  • Maintainability: Improved the maintainability as one place change and it will reflect on all the places.

5. Cons of Using Custom ViewModifiers

  • Overhead: Creating numerous custom modifiers for small styling changes might lead to an excessive number of modifiers, making it hard to manage.

6. Best Practices for Using Custom ViewModifiers

  • Avoid Overuse: Use custom ViewModifiers judiciously for significant and reusable view manipulations. For minor changes, consider using the built-in modifiers provided by SwiftUI.
  • Documentation: Properly document our custom modifiers to make it easier for other developers (and your future self) to understand their purpose and usage.
If you appreciate my work, please give me a round of applause.

--

--

Santosh Botre

Take your time to learn before develop, examine to make it better, and eventually blog your learnings.