ContentUnavailableView for creating Empty States with SwiftUI
At WWDC 2023, Apple introduced a new view in SwiftUI called ContentUnavailableView
. This view allows us to create empty states. Let's see an example of how to create this view:
ContentUnavailableView {
// 1
Label("Title", systemImage: "image")
// 2
} description: {
Text("Description")
// 3
} actions: {
Button {
print("Action")
} label: {
Text("Create Food")
}
}
- We define a
Label
with a title and an image. - We add an optional description.
- We add the action we want to perform, in this case, a button, which is also optional.
Adding ContentUnavailableView in Our View
Imagine we receive a list of foods from the server, and it arrives empty due to an error in the call or because we genuinely have no added foods in our list. We create our list of foods and add the ContentUnavailableView
within an overlay
modifier, with the condition that the view should be shown if our foods
variable is empty.
Then we add a Label
with a title and the image we want to represent to the ContentUnavailableView
, followed by a description to inform the user of what is happening.
import SwiftUI
struct ContentView: View {
var foods: [String] = []
var body: some View {
List {
ForEach(foods, id: \.self) { food in
Text(food)
}
}
.overlay {
if foods.isEmpty {
ContentUnavailableView {
Label("No Food", systemImage: "carrot.fill")
} description: {
Text("Start adding food to see them in your list")
}
}
}
}
}
Let’s see how the view looks:
Different Ways to Create a ContentUnavailableView
- Adding a
Label
, description, and action, as we saw in the first section of the article. - Using the option provided by Apple to create an empty state for a failed search:
ContentUnavailableView.search
.
3. The same option as above, but adding the not-found search term: ContentUnavailableView.search(text: "AsyncLearn")
.
Thanks to this new view provided by Apple, we can easily and quickly create empty states, improving the user experience in our app.
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/content-unavailable-view-swiftui-empty-states/