Using View Modifiers to Display Empty State
Replicating Apple's Reminders app
Empty state is an important aspect of UX - it’s what users see when they first open your app, and as the saying goes, there is no second chance to leave a first impression - so it better be good. Showing users a meaningful empty state will make them feel welcome and is a great opportunity for you to educate them about how to get started with the app.
So far, Make It So doesn’t display a meaningful empty state, and in this article, we will look at a couple of options to implement this.
What we’re going to build
To get started, let’s take a look at Apple’s Reminder app (since this is the app that we’re trying to replicate):
A simple way to implement empty state is to use Xcode’s Make Conditional refactoring (CMD + Click on a view, then choose Make Conditional). This will wrap the view in an
if ... else statement and wrap the entire structure in a
Not too bad, but this adds visual noise to the code for our view - let’s see if we can improve this.
Using a ViewModifier to Manage Empty State
View Modifiers are one of the main features of SwiftUI that make writing SwiftUI code an enjoyable experience. Without view modifiers, the only way to configure views would be their initialisers, resulting in a pretty terrible developer experience.
Thanks to view modifiers, we can configure views like this:
instead of this (hypothetical code):
At the call site, a view modifier for adding empty state to a view might look like this:
Let’s take a look at how to build this. View modifiers usually consist of two parts: the view modifier itself, and an extension to make it easier to use.
Let’s start with the view modifier:
All view modifiers can access the view they operate on via the
content: Content parameter of the
body function. In addition, we’ve declared two properties:
isEmptylets the caller indicate whether or not to display the empty state
emptyContentis a closure that returns the view we want to display in case
Depending on the state of the
isEmpty property, we will either display the
emptyContent, or the original view, which we can access via the
To use this modifier on a view, we’d have to write the following:
Which doesn’t look very user friendly.
Adding an Extension to Improve the Developer Experience
Let’s define an extension on
View to make this easier to use:
And now we can use the view modifier as expected. Here is the main list view of Make It So, with the view modifier applied:
Thanks for reading! 🔥