使用部分过滤SwiftUITableView的问题-未显示结果
本质上,我有一个 tableview,它显示了一个名称数组并将它们分成几个部分 - 我最近添加了一个搜索栏来过滤数据,但是我在呈现过滤数据时遇到了问题,我没有收到任何错误,只是一个空数组集.
以下是我如何呈现/尝试过滤数据:
var sections = [customerListSection]()
var structure = [customerList]()
var filteredSections = [customerListSection]()
var filteredStructure = [customerList]()
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filteredStructure = structure.filter({( customers : customerList) -> Bool in
return customers.customer.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
从我的测试来看,No Customers每次我尝试使用搜索时都会出现打印件,这让我认为filteredSections 没有被更新。有什么想法吗?见下文:
override func numberOfSections(in tableView: UITableView) -> Int {
if isFiltering() {
if filteredSections.count == 0 {
print("No Customers")
} else {
tableView.restore()
}
return filteredSections.count
}
if sections.count == 0 {
} else {
tableView.restore()
}
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
return filteredSections[section].items.count
}
return sections[section].items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//let item = sections[indexPath.section].items[indexPath.row]
let customerList: customerList
if isFiltering() {
customerList = filteredSections[indexPath.section].items[indexPath.row]
cell.textLabel!.text = customerList.customer
} else {
customerList = sections[indexPath.section].items[indexPath.row]
cell.textLabel!.text = customerList.customer
}
return cell
}
结构:
struct customerListSection {
let customerType : String
var items : [customerList]
}
struct customerList: Decodable {
let customerid: Int
let customer: String
let type: String
}
这就是我使用 json 填充 tableview 的方式:
private func fetchJSON() {
guard let url = URL(string: "server.com")
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "value=1".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode([customerList].self, from: data)
let grouped = Dictionary(grouping: res, by: { $0.type })
var keys = grouped.keys.sorted()
if let index = keys.firstIndex(of: "Display On Top") {
let first = keys.remove(at: index)
keys.insert(first, at: 0)
}
self.sections = keys.map({customerListSection(customerType: $0, items: grouped[$0]!)})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
}