arrays - 带有搜索器的 Tableview - 搜索效果很好,但选择元素显示错误的元素
问题描述
我的 tableView 有问题,我在其中显示一些值供用户选择。它与一个搜索栏连接,该搜索栏过滤 TableView 中显示的数组中的内容。
所以问题如下:当我搜索一个元素时,tableView 完美过滤,显示正确的元素。但是如果我决定选择这个元素,它将显示从一开始就显示的第一个元素,即从将所有元素加载到 textView 中。就像我的 tableView 在搜索时只显示文本而不显示正确的 indexPath 一样。
这是代码:
extension SelectCityViewController: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchCity.count
} else {
return citiesItems.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if searching {
cell?.textLabel?.text = searchCity[indexPath.row]
} else {
cell?.textLabel?.text = citiesItems[indexPath.row]
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
toastMessage(message: "\(citiesItems[indexPath.row]) selected")
SelectCityViewController.selectedCity="\(citiesItems[indexPath.row])"
self.removeAnimate()
}
}
extension SelectCityViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchCity = citiesItems.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tableView.reloadData()
}
解决方案
你应该检查状态是否在searching
/不在didSelectRowAt
if searching {
selectCityViewController.selectedCity = searchCity[indexPath.row]
}
else {
selectCityViewController.selectedCity = citiesItems[indexPath.row]
}
也有短途
selectCityViewController.selectedCity = searching ? searchCity[indexPath.row] : citiesItems[indexPath.row]
此外,如果searchCity[indexPath.row]
/citiesItems[indexPath.row]
的类型String
则不需要"\()"
推荐阅读
- html - 如何使用 col-sm 内联?
- azure - Databricks 文件存储 = 0
- android - Android应用程序忽略用户应用程序权限
- c++ - 我需要帮助修复 C++ 空白检测器
- javascript - 如何解决 ChartJS 甜甜圈选项中的语法错误?
- android - 如何使用处理程序运行重复任务
- python - Bazel 0.26.1 在 py_test 上使用 Python3
- lua - 有没有办法让用 Luarocks 安装的 Lua 脚本在运行时找到它的安装前缀?
- hadoop - 提前知道 Hive 行将去哪个桶
- java - Spring手动创建组件并注册为单例