Im currently creating an app that has a list of locations on a uitableview. There is also a filtering function so that the locations can be filtered based on categories. When not filtering, the uitableviewcell performs the segue when clicked and the correct data gets loaded in the destination viewcontroller. However when I filter tableview, the cells get populated with the right data, but when I click the cell, the destination viewcontroller always loads the data from the first cell in the UNFILTERED tableview.
The code that I am using:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "shoutoutCell", for: indexPath) as! shoutoutTableViewCell
var shout = shoutout[indexPath.row]
if isFiltering == true {
shout = filteredShoutout[indexPath.row]
} else {
shout = shoutout[indexPath.row]
}
cell.shoutout = shout
cell.showsReorderControl = true
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var object = shoutout[indexPath.row]
if isFiltering == true {
object = filteredShoutout[indexPath.row]
} else {
object = shoutout[indexPath.row]
}
performSegue(withIdentifier: "shoutoutDetailSegue", sender: object)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "shoutoutDetailSegue" {
if let destination = segue.destination as? shoutoutDetailViewController {
// destination.shoutoutSelected = sender as! object
destination.shoutoutSelected = shoutout[(tableView.indexPathForSelectedRow?.row)!]
}
}
}
This is happening because you are using shoutout
Array in prepare(for segue
even when filtering.
destination.shoutoutSelected = shoutout[(tableView.indexPathForSelectedRow?.row)!]
Change it to
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "shoutoutDetailSegue" {
if let destination = segue.destination as? shoutoutDetailViewController {
// Here `Model` should be your class or struct
destination.shoutoutSelected = sender as! Model
}
}
OR move your logic here from didSelectRowAt
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "shoutoutDetailSegue" {
if let destination = segue.destination as? shoutoutDetailViewController {
if isFiltering == true {
object = filteredShoutout[indexPath.row]
} else {
object = shoutout[indexPath.row]
}
destination.shoutoutSelected = object
}
}