Внутри вашего метода tableView (: didSelectRowAt) вы жестко закодировали индексы от 0
до 3
.Однако ваш tableView переключается между коллекциями Array
и Filter
.Более того, данные в коллекции Filter
могут изменяться в зависимости от текста в поле поиска.
Вы можете решить это, как написано @Sh_Khan.Но, возможно, лучше бы иметь отфильтрованную коллекцию, привязанную к tableView, и неизмененную коллекцию, содержащую все данные.
Таким образом, вам не нужно проверять, установлен ли isSearching
в каждомметод.На самом деле, вам это вообще не нужно.Вам просто нужно сделать следующее:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Filter.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
cell.CellLabel.text = Filter[indexPath.row]
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
view.endEditing(true)
Filter = Array.compactMap({ $0 }) // Copies all elements from Array
} else {
Filter = Array.filter({ $0.contains(searchBar.text!) })
}
TableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(Filter[indexPath.row])
}