使用.searchable构建搜索视图

2个月前 168次点击 来自 iOS

注:SwiftUI Release 3.0 或 iOS15后有效

参考文章:Mastering search in SwiftUI

在之前的文章iOS15后使用.searchable实现简单的数据过滤 , 笔者分享了.searchable的基础使用,这是另外一篇查漏补缺文章。

假设,你已经准备好SearchViewModel数据源,通过在.onChange回调方法中进行数据检索:

struct ContentView: View {
    @StateObject private var viewModel = SearchViewModel()
    @State private var query = ""

    var body: some View {
        NavigationView {
            List(viewModel.repos) { repo in
                VStack(alignment: .leading) {
                    Text(repo.name)
                        .font(.headline)
                    Text(repo.description ?? "")
                        .foregroundColor(.secondary)
                }
            }
            .navigationTitle("Search")
            .searchable(text: $query)
            .onChange(of: query) { newQuery in
                async { await viewModel.search(matching: query) }
            }
        }
    }
}

SwiftUI为 .searchable 提供了新的Environment变量isSearching,dismissSearch,看名字就知道干啥使得:

struct StarredReposList: View {
    @StateObject var viewModel = SearchViewModel()
    @Environment(\.dismissSearch) var dismissSearch
    @Environment(\.isSearching) var isSearching

    let query: String

    var body: some View {
        List(viewModel.repos) { repo in
            RepoView(repo: repo)
        }.overlay {
            if isSearching && !query.isEmpty {
                VStack {
                    Button("Dismiss search") {
                        dismissSearch()
                    }
                    SearchResultView(query: query)
                        .environmentObject(viewModel)
                }
            }
        }
    }
}
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签