LVT9
LVT9

Reputation: 33

Tableview with searcher - Searching works good, but selecting element displays wrong element

I'm having a problem with a tableView where I display some values for the user to choose. It is connected with a search-bar that filters the contents in an array displayed in the TableView.

So the problem is as follows: When I search for an element, the tableView filters perfectly, displaying the correct element. But if I decide to choose this element, it will display the first element that were showed from beginning, i.e. from loading all the elements into the textView. It's like my tableView only displays the text but not the correct indexPath when searching.

Here is the code:

    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()
    }

Upvotes: 1

Views: 48

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You should check whether the state is searching / not in didSelectRowAt

if searching {
   selectCityViewController.selectedCity = searchCity[indexPath.row]
 }
 else {
   selectCityViewController.selectedCity = citiesItems[indexPath.row]
 }

A short way also

selectCityViewController.selectedCity = searching ? searchCity[indexPath.row] : citiesItems[indexPath.row]

Also if type of searchCity[indexPath.row] / citiesItems[indexPath.row] is String then no need for "\()"

Upvotes: 1

Related Questions