gpt4 book ai didi

ios - 从 TableView 中删除单元格后更新 indexPath.row

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:52 25 4
gpt4 key购买 nike

我有一个表格 View ,其中的单元格在点击时根据 indexPath 显示不同的表格 View ,即:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nc = UINavigationController()
let productController = ProductController()
nc.viewControllers = [productController]

//Apple
if (indexPath.row == 0) {
productController.navigationItem.title = "Apple Products";
}
//Google
if (indexPath.row == 1) {
productController.navigationItem.title = "Google Products";
}
//Twitter
if (indexPath.row == 2) {
productController.navigationItem.title = "Twitter Products";
}
//Tesla
if (indexPath.row == 3) {
productController.navigationItem.title = "Tesla Products";
}
//Samsung
if (indexPath.row == 4) {
productController.navigationItem.title = "Samsung Products";
}
present(nc, animated: true, completion: nil)
}

但是当我像这样删除一个单元格时......

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
tableView.beginUpdates()
CompanyController.companies.remove(at: indexPath.row)
CompanyController.logos.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}

....indexPath 未更新,因此如果我删除 Apple 单元格(在 indexPath.row 0),Google 单元格将取而代之,但仍会指向 Apple 产品页面,依此类推其余公司。我认为 tableView.delete 行行正在处理这个问题,但事实并非如此。删除内容后如何更新 indexPath?

最佳答案

不要对数据进行硬编码并假定特定的行。将数据放入数组中,根据索引路径从数组中取值。当一行被删除时,通过从数组中删除来更新您的数据模型。

将您的 didSelectRow 方法更新为:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nc = UINavigationController()
let productController = ProductController()
nc.viewControllers = [productController]

productController.navigationItem.title = CompanyController.companies[indexPath.row]
present(nc, animated: true, completion: nil)
}

关于ios - 从 TableView 中删除单元格后更新 indexPath.row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com