首页 > 解决方案 > 带有搜索器的 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()
    }

标签: arraysswiftsearchtextviewelement

解决方案


你应该检查状态是否在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 则不需要"\()"


推荐阅读