Kyriakos Karslidis
Kyriakos Karslidis

Reputation: 25

tableView.dequeueReusableCell opens wrong ViewController

i have an array and i've created a seperate vc for each array item, tableView.dequeueReusableCell shows wrong vc. I've read that this is because the cell is reusable and it keeps the data from the previous selected array. Can you please help me to fix it.

My code is:

import UIKit

class Nicosia: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let nicosiaPlaces = ["Famagusta Gate", "Laiki Geitonia", "Ledra Street","Omeriye Hamam","Cyprus Museum","Venetian Walls","The House of Hatjigeorgakis Kornessios","Byzantine Art Museum","Archbishop's Palace","Liberty Monument","The Faneromeni Church","Nicosia International Conference Center"]

     var identities = ["Famagusta Gate", "Laiki Geitonia", "Ledra Street","Omeriye Hamam","Cyprus Museum","Venetian Walls","The House of Hatjigeorgakis Kornessios","Byzantine Art Museum","Archbishop's Palace","Liberty Monument","The Faneromeni Church","Nicosia International Conference Center"]

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nicosiaPlaces.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        let city = nicosiaPlaces [indexPath.row]
        cell?.textLabel?.text = city
        return cell!
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        let vcName = identities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
        self.navigationController?.pushViewController(viewController!, animated: true)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}

Upvotes: 0

Views: 138

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Replace this

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)

with

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

Upvotes: 1

rmaddy
rmaddy

Reputation: 318814

You mean didDeselectRowAt, not dequeueReusableCell.

And the problem is that you want didSelectRowAt, not didDeselectRowAt.

Upvotes: 1

Related Questions