SwiftUI搜索栏的功能是通过结构数组进行搜索



我想在列表视图上实现搜索栏功能。下面是我当前的代码:

Section(header: SearchBar(text: self.$searchQuery)) {
List(fetcher.user) { user in
HStack() {
Text(user.name)
}
}
}

其中用户被声明为@Published var user = [User]()

如何实现搜索功能?我看过一些视频,但它们的用例比我的要简单得多,因为我试图通过一组结构执行搜索。

我会使用ObservableObject来执行搜索逻辑:

class SearchHandler: ObservableObject {
var searchText: String = "" {
didSet {
search()
}
}
// Your array, replace String with your type
@Published var resultObjs: [String] = []
// Your initial array, replace String with your type
var allObjs: [String]
init(allObjs: [String]) {
self.allObjs = allObjs
}
func search() {
// Write all your searching code here
// Use the searchText variable to filter out object
// from allObjs and write them into resultObjs
}
}

它是一个可以向侦听器发布值的类,在这种情况下,它将是您的SwiftUI视图。

然后你可以这样使用它:

struct ContentView: View {
// Replace the empty array with your initial data
@ObservedObject var searchHandler = SearchHandler(allObj: [])
var body: some View {
Section(header: SearchBar(text: self.$searchHandler.searchText)) {
List(self.$searchHandler.$resultObj) { user in
HStack() {
Text(user.name)
}
}
}
}
}

最新更新