我终于有了工作代码来搜索对象数组,但是在视图中填充/显示列表结果真的很慢。我一直在研究使用 ObservableObject 和 EnvironmentObject 但我不确定如何在这里实现它们。我正在导入 CSV 并将标题用作键并将行项用作值,然后将它们显示在列表中。当我尝试搜索某些内容时,列表会重新填充,但需要很长时间。任何帮助将不胜感激!!!
ListView.swift
import Foundation
import SwiftUI
var arrayOfData = [Container]()
struct ListView: View {
@State private var searchTerm: String = ""
@State private var array: [Container] = []
//@State var array: [Container] = newArray
func arrayFiller(){
if arrayOfData.count > 0 {
arrayOfData.removeAll()
}
for item in csvArray {
arrayOfData.append(Container(
barcode: item["Barcode"],
model: item["Model"],
description: item["ASDescription"],
serial: item["Asset Serial No"],
building: item["Building"],
floor: item["Floor"],
room: item["Room"]))
}
}
init() {
// UITableView.appearance().separatorColor = .clear
//Build list of headers using the top view.
arrayFiller()
}
var body: some View {
List {
SearchBar(text: $searchTerm, array: $array)
ForEach(array, id:\.self){item in
Text("\(item.barcode ?? "")")}
}
}
}
搜索栏.swift
struct SearchBar: UIViewRepresentable {
@Binding var text: String
@Binding var array: [Container]
class Coordinator: NSObject, UISearchBarDelegate, ObservableObject {
@Binding var text: String
@Binding var array: [Container]
init(text: Binding<String>, array: Binding<[Container]>) {
_text = text
_array = array
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
array = [Container]()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.array = arrayOfData.filter {
self.text.isEmpty ? true : (($0.barcode?.localizedCaseInsensitiveContains(self.text))!)}
}
print(array)
}
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text, array: $array)
}
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}