一、基本用法
- SwiftUI 引入了新的 ContentUnavailableView 类型,允许在应用程序中展示空状态、错误状态或任何其他内容不可用的状态。那么,如何使用 ContentUnavailableView 引导用户浏览应用程序中的空状态呢?
- 首先看看 ContentUnavailableView 视图的基本用法:
struct ContentView: View {let store: Storevar body: some View {NavigationStack {List(store.products, id: \.self) { product inText(verbatim: product)}.navigationTitle("Products").overlay {if store.products.isEmpty {ContentUnavailableView("Connection issue",systemImage: "circle")}}}}
}

- 在这个示例中,将 ContentUnavailableView 定义为产品列表的叠加层。每当产品列表为空时,使用带有标题和图像的 ContentUnavailableView 显示,ContentUnavailableView 的另一种变体还允许定义当前状态的描述文本。
二、自定义视图
- ContentUnavailableView 还允许在描述文本下方显示操作按钮。因此,ContentUnavailableView 初始化程序的另一种变体允许我们使用 ViewBuilder 闭包定义视图的每个部分,从而完全自定义其外观和感觉。
struct ContentView: View {let store: Storevar body: some View {NavigationStack {List(store.products, id: \.self) { product inText(verbatim: product)}.navigationTitle("Products").overlay {if store.products.isEmpty {ContentUnavailableView {Label("Connection issue", systemImage: "wifi.slash")} description: {Text("Check your internet connection")} actions: {Button("Refresh") {store.fetch()}}}}}}
}

三、搜索屏幕使用
- 在搜索屏幕显示搜索结果时,可以使用 ContentUnavailableView 类型的搜索功能。它由框架本地化,并遍历视图层次结构以找到搜索栏并提取其文本以显示在视图内。
struct ContentView: View {@Bindable var store: Storevar body: some View {NavigationStack {List(store.products, id: \.self) { product inText(verbatim: product)}.navigationTitle("Products").overlay {if store.products.isEmpty {ContentUnavailableView.search}}.searchable(text: $store.query)}}
}

四、手动提供查询
- 还可以通过使用 ContentUnavailableView 类型的搜索功能并提供单个参数来手动将查询输入描述中:
struct ContentView: View {@Bindable var store: Storevar body: some View {NavigationStack {List(store.products, id: \.self) { product inText(verbatim: product)}.navigationTitle("Products").overlay {if store.products.isEmpty {ContentUnavailableView.search(text: store.query)}}.searchable(text: $store.query)}}
}

五、完整可运行示例
- 由于代码片段中的 Store 类型未提供,使用一个简化版本的示例代码来创建一个简单的 SwiftUI Demo,以展示 ContentUnavailableView 的基本使用。创建一个简单的 Product 结构体表示产品,以及一个 ProductStore 类作为存储产品的模拟服务。在 ContentView 中,使用 ContentUnavailableView 来处理产品为空的情况。
import SwiftUIstruct Product: Identifiable {let id: UUIDlet name: String
}class ProductStore: ObservableObject {@Published var products: [Product] = []func fetchProducts() {DispatchQueue.main.asyncAfter(deadline: .now() + 2) {self.products = [Product(id: UUID(), name: "iPhone"), Product(id: UUID(), name: "iPad")]}}
}struct ContentView: View {@StateObject var store = ProductStore()var body: some View {NavigationView {List(store.products) { product inText(product.name)}.navigationTitle("Products").overlay {if store.products.isEmpty {ContentUnavailableView("No Products",systemImage: "exclamationmark.triangle")}}.onAppear {store.fetchProducts()}}}
}struct ContentView_Previews: PreviewProvider {static var previews: some View {ContentView()}
}
- 请确保在 Xcode 中创建一个新的 SwiftUI 项目,并将上述代码替换到主 ContentView 中,然后运行该项目。在项目的初始加载时,ContentUnavailableView 将显示“No Products”消息,几秒后模拟产品加载,之后产品列表将显示在主视图中。