UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.