ContentUnavailableView - Handling Empty Views
ContentUnavailableView is one of the newly introduced features at WWDC 2023, where iOS 17 was announced. Besides being one of the newly introduced features at WWDC 2023 where iOS 17 was announced, it's actually a display template that can be very useful for those working with SwiftUI.
With this tool, whether it's a search section or specific task screens, you can benefit directly from this template without creating a new screen if no results are returned.
In this simple-to-use template, the only thing you need to be aware of is using it in conjunction with the overlay feature.
You can see this in the example code snippet published in Apple's official documentation:
Also you can define the view you call like this:
If you want to see the complete example, the code looks like this:
With this tool, whether it's a search section or specific task screens, you can benefit directly from this template without creating a new screen if no results are returned.
In this simple-to-use template, the only thing you need to be aware of is using it in conjunction with the overlay feature.
You can see this in the example code snippet published in Apple's official documentation:
.overlay {
if searchResults.isEmpty {
ContentUnavailableView.search
}
}
Also you can define the view you call like this:
ContentUnavailableView {
Label("No Results", systemImage: "tray.fill")
} description: {
Text("Check the spelling or try a new search.")
}
If you want to see the complete example, the code looks like this:
struct ContentView: View {
@ObservedObject private var viewModel = ContactsViewModel()
var body: some View {
NavigationStack {
List {
ForEach(viewModel.searchResults) { contact in
NavigationLink {
ContactsView(contact)
} label: {
Text(contact.name)
}
}
}
.navigationTitle("Contacts")
.searchable(text: $viewModel.searchText)
.overlay {
if searchResults.isEmpty {
ContentUnavailableView.search
}
}
}
}
}