arrays - 带有搜索器的 Tableview - 搜索效果很好,但选择元素显示错误的元素

标签 arrays swift search textview element

我在使用 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/not in 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 则不需要 "\()"

关于arrays - 带有搜索器的 Tableview - 搜索效果很好,但选择元素显示错误的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53907307/

相关文章:

search - B+ 树插入/搜索?

c - 程序C-搜索,如何知道它是二进制搜索还是线性搜索?

c - 你能多快进行线性搜索?

javascript - 找到对象数组angularjs的索引

javascript - 如何从对象返回值?

javascript - 在 div 中显示 javascript 数组

arrays - Swift - 循环数组并添加到 UICollectionView

python - 通过分布项乘以 Numpy 数组

json - 保持用户快速登录

javascript - didSet 在 Javascript : calling function when variable is altered