How to Handle Empty States Using UIContentUnavailableConfiguration
This article is originally published at swiftsenpai.com
In this year WWDC (WWDC23), Apple surprised developers with an unexpected improvement to UIKit. The introduction of
UIContentUnavailableConfigurationaimed to simplify the process of creating empty states for view controllers.
According to Apple,
UIContentUnavailableConfiguration is a composable description of an empty state and can be provided with placeholder content, such as an image or text.
Here’s an example of an empty state showcased in WWDC:
Now, let’s get into the details.
This article primarily focuses on the UIKit side of things. If you’re interested in learning how to do the same thing in SwiftUI, I recommend checking out this article by Antoine van der Lee.
Creating a UIContentUnavailableConfiguration
There are essentially 4 ways to create a
- Creating from scratch
- Using the predefined loading configuration
- Using the predefined search configuration
1. Creating from Scratch
To start from scratch, we must first create an empty
var config = UIContentUnavailableConfiguration.empty()
After that, we will have to configure the
UIContentUnavailableConfiguration‘s placeholder content based on our needs:
config.image = UIImage(systemName: "applelogo")
config.text = "WWDC23 Demo"
config.secondaryText = "Code new worlds."
Lastly, simply set the configuration to the view controller’s
self.contentUnavailableConfiguration = config