Search code examples
iosswiftuitableviewdidselectrowatindexpath

didSelectRowAt indexPath: IndexPath - is always returning the previous selection


I have a UITableView, a custom class for the custom cell and my ViewController swift:

private var model_firma = [Firme]()
var firme = Firme(IDFirma: 1, Denumire: "ZZZZZ", Reprezentant: "JohnDoe")
    model_firma.append(firme);
    firme = Firme(IDFirma: 2, Denumire: "YYYYYYY", Reprezentant: "JohnDoe")
    model_firma.append(firme);

And:

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

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! FirmeTableViewCell
        let item = cell.labelDenumire
        labelSelectedCompany.text = item?.text
}

The items are displayed correctly. But, at the first click on the tableview, on any item, nothing happen. At the second click || selection on a different item, the previous item is retrieved.

The function I use to add rows to the UITableView using the data from the model :

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

let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! FirmeTableViewCell
let text = model_firma[indexPath.row]

cell.labelDenumire.textColor = UIColor(rgb: 0xffffff)
cell.labelDenumire.text = text.Denumire

It seems that I can't figure it out by my myself.

Thank you very much!


Solution

  • Logically, in the didSelectRowAt I would assume that you should read the desired data from the the data source (model_firma) directly instead of getting the cell and read from it:

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let currentModel = model_firma[indexPath.row]
        labelSelectedCompany.text = currentModel.Denumire
    }
    

    Sidebar Notes:

    • In Swift, we usually follow the camel case naming convention:
      • modelFirma instead of model_firma.
      • variable names should start with a small letter: denumire instead of Denumire.

    Instead of:

    private var model_firma = [Firme]()
    var firme = Firme(IDFirma: 1, Denumire: "ZZZZZ", Reprezentant: "JohnDoe")
        model_firma.append(firme);
        firme = Firme(IDFirma: 2, Denumire: "YYYYYYY", Reprezentant: "JohnDoe")
        model_firma.append(firme);
    

    preferably, it should be as:

    private var firmes = [Firme(IDFirma: 1, Denumire: "ZZZZZ", Reprezentant: "JohnDoe"),
                          Firme(IDFirma: 2, Denumire: "YYYYYYY", Reprezentant: "JohnDoe")]
    

    with removing the ;.