使用.searchable构建搜索视图


8个月前 419次点击 来自 移动端

标签: SwiftUI

注: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)
                }
            }
        }
    }
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑