【问题标题】:How to select the correct entity in didSelectRowAt indexPath如何在 didSelectRowAt indexPath 中选择正确的实体
【发布时间】:2020-03-31 22:59:17
【问题描述】:

我的tableviewname 属性排序。因此,如果我输入名称“Hanna”然后“Belle”tableview 将如下所示:


美女


汉娜


但是当我选择一个单元格时,由于我猜是我输入的顺序,会显示来自另一个单元格的数据。我该如何解决这个问题?

MainTableViewController.swift

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MainTableViewCell

    let pet = fetchedResultsController.object(at: indexPath)

    cell?.nameLB.text = pet.name
    if pet.isDog {
        cell?.isDogString = "dog"
        cell?.petImage.image = UIImage(named: "dog.png")
    } else {
        cell?.isDogString = "cat"
        cell?.petImage.image = UIImage(named: "cat.png")
    }
    if pet.isBoy {
        cell?.backgroundColor = UIColor(red: 102/255, green: 230/255, blue: 255/255, alpha: 1.0)
    } else {
        cell?.backgroundColor = UIColor(red: 255/255, green: 153/255, blue: 255/255, alpha: 1.0)
    }
    return cell!
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "PetSelectedViewController") as! PetSelectedViewController
    vc.pet = pets[indexPath.row]
    _ = navigationController?.pushViewController(vc, animated: true)
}

PetSelectedViewController.swift

var pet: Pet! // entity

override func viewDidLoad() {
    super.viewDidLoad()
    basicPetInfoUI()
    loadData()
}

func loadData() {
    var isBoyString = ""
    var isVaccString = ""
    pet!.isBoy ? (isBoyString = "Boy") : (isBoyString = "Girl")
    pet!.isVaccinated ? (isVaccString = "Vaccinated") : (isVaccString = "Not Vaccinated")
    nameLabel.text = pet.name
    breedLabel.text = pet.breed
    isBoyLabel.text = isBoyString
    isVaccinatedLabel.text = isVaccString
    weightLabel.text = pet.weight
}

如果需要更多信息,请告诉我,我将编辑我的问题。

【问题讨论】:

  • 你是怎么设置var pet: Pet!的?
  • 可以添加cellForRow的代码吗?
  • didSelectRowAt 中的固定行并添加了 cellForRow

标签: ios swift uitableview core-data didselectrowatindexpath


【解决方案1】:

cellForRowAt 内部你使用fetchedResultsController

let pet = fetchedResultsController.object(at: indexPath)

但在didSelectRowAt 内部你使用pets

vc.pet = pets[indexPath.row]

你必须在两者中使用相同的数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多