didSelectRowAt indexPath:IndexPath-始终返回上一个选择

时间:2018-09-10 13:37:23

标签: ios swift uitableview didselectrowatindexpath

我有一个UITableView,一个用于自定义单元格的自定义类和我的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);

并且:

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
}

项目正确显示。 但是,第一次单击表视图时,任何项目都不会发生。在第二次单击||。选择其他项目,则检索上一个项目。

该函数用于使用模型中的数据向UITableView添加行:

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

似乎我自己无法弄清楚。

非常感谢您!

1 个答案:

答案 0 :(得分:1)

从逻辑上讲,我假设在didSelectRowAt中,您应该直接从数据源(model_firma)中读取所需的数据,而不是获取单元格并从中读取数据:

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

侧边栏注释:

  • 在Swift中,我们通常遵循 camel case 命名约定:
    • modelFirma而不是model_firma
    • 变量名称应以小写字母开头:denumire,而不是Denumire

代替:

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);

最好应为:

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

同时删除了;

相关问题