TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Showing empty states with ContentUnavailableView

Paul Hudson    @twostraws   

SwiftUI's ContentUnavailableView shows a standard user interface for when your app has nothing to display. I know, that sounds redundant, right? After all, if you have nothing to display, you have nothing to display!

But ContentUnavailableView is perfect for times your app relies on user information that hasn't been provided yet, such as when your user hasn't created any data, or if they are searching for something and there are no results.

As an example, if you were making an app that let users write down Swift code snippets they wanted to remember, it might start with no snippets by default. So, you could use ContentUnavailableView like this:

ContentUnavailableView("No snippets", systemImage: "swift")

That will show a big Swift icon from SF Symbols, plus title text below saying "No snippets".

You can also add an extra line of description text below, specified as a Text view so you can add extra styling such as a custom font, or a custom color:

ContentUnavailableView("No snippets", systemImage: "swift", description: Text("You don't have any saved snippets yet."))

And if you want full control, you can provide individual views for the title and description, along with some buttons to display to help the user to get started:

ContentUnavailableView {
    Label("No snippets", systemImage: "swift")
} description: {
    Text("You don't have any saved snippets yet.")
} actions: {
    Button("Create Snippet") {
        // create a snippet
    }
    .buttonStyle(.borderedProminent)
}

It's a really simple view to use, but it's much better than just showing a blank screen when the user first comes to your app!

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.