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

问题描述 投票:2回答:1

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

Section(header: SearchBar(text: self.$searchQuery)) {

            List(fetcher.user) { user in

                HStack() {

                    Text(user.name)

                }

            }

        }

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

我该如何实施搜索功能?我看过一些视频,但是它们的用例比我的要简单得多,因为我正在尝试通过结构数组进行搜索。

search swiftui
1个回答
0
投票

我将使用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)
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.