When I started to investigate SwiftUI I was organising some presentation in the weekly iOS tech session for the company I work. My focus was to present how to use the basics and the @EnvironmentObject, @State, @ObservedObject.
Later I started the first project and it was a real challenge, with animations and visual component that will cause a lot of pain to do using UIKit. The final result was very good, the code was what we have as knowledge in that time, but it shown how good SwiftUI is.
Then I start to get more in ViewModifiers than trying to create views to encapsulate the changes I wanted.
View or ViewModifier?
Let’s assume I am going to implement a View to increase the size based on more simple numbers to generate big font sizes, or in this case using Emojis.
I want easily have big palm tree 🌴 in my screen like the one below.
If I am going to implement this as a View the code will look something like this:
Cool! It works!
Now the ViewModifier version:
We can spot 2 main differences:
- The ViewModifier receives only one parameter
- The implementation of the ViewModifier is private, so you only access the extension available inside the View
The outcome is the same, but ViewModifier is an elegant and much more reusable way.
Chain of changes
We might argue that the ViewModifiers are different from Views because modifiers are applied over Views, but the principle is the same in this case.
A View also can modify another View, to do that you just pass the content you want to modify as parameter.
To make it work, we need to pass the content of the View as parameter. It can be any View, so now you don’t need to pass a text and create an element Text inside.
For showing this I will create a button inspired by the 2000 Aqua graphical designs from Apple. Actually a very simplified version.
A ViewModifier implementation is very similar, however, because of the syntax of the modifiers when extended inside views, the modifier we create only add another line and apply to the result View above it.
View and ViewModifiers can be used for the same reason, but ViewModifiers are much more elegant and make the code more readable.
Even looking very similar, ViewModifier is much more powerful when you start to using with animations. I will write more about it in another article.