我有一个 tablewView,上面有一个城市列表和一个搜索栏。如果有很多城市,我想给用户使用搜索的机会。
我输出这样的数据:
我有一堂课:
class City {
var id: Int?
var name: String?
}
我得到一个城市列表和它们的 ID,并创建一个 City 类的数组,我用接收到的数据填充它。我立即创建了一个数组filteredData,它在初始化时等于所有城市的列表——基于这个数组,我更新了表。
override func viewDidLoad() {
super.viewDidLoad()
loadCity() // Тут скрипт, который загружает список городов в массив citiesList
searchBarController.delegate = self
filteredCitiesList = citiesList
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredCitiesList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = filteredCitiesList[indexPath.row].name
return cell
}
接下来,如果用户在搜索中输入数据并更新表,我实际上是在尝试在filteredCitiesList 数组中实现更改,但我不知道该怎么做。
这是我找到的代码。如果我只有一个字符串数组,它可能会起作用,但由于我有一个我自己的类(城市)的对象数组,它发誓(“'String'不可转换为'City'”),但如何修复我的知识已经不够了。帮助)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredCitiesList = searchText.isEmpty ? citiesList : citiesList.filter { (item: String) -> Bool in
return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
tableView.reloadData()
}
如果有人也有兴趣,我找到了一种实现任务的方法 - 这是最终的工作版本: