【问题标题】:Updating indexPath.row after deleting a cell from table view从表视图中删除单元格后更新 indexPath.row
【发布时间】:2016-12-06 00:34:55
【问题描述】:

根据 indexPath,我有一个表格视图,其中的单元格在点击时呈现不同的表格视图,即:

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 rows 行正在处理这个问题,但事实并非如此。删除某些内容后如何更新 indexPath?

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

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

    将您的 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)
    }
    

    【讨论】:

    • 我的印象是我正在做的事情 - 我的数据在数组(公司、徽标)中,表格使用 cell.textLabel?.text = CompanyController.companies[indexPath.row ]。然后当我删除时,我使用 CompanyController.companies.remove(at: indexPath.row) 从数组中删除。
    • 但是您在 didSelectRowAt 方法中硬编码字符串和行号。删除所有这些if 语句,只使用productController.navigationItem.title = CompanyController.companies[indexPath.row]
    • 好的,现在太棒了!从来没想过这样做,但它是如此合乎逻辑。非常感谢您的帮助!
    • 很高兴为您提供帮助。如果你发现自己写了一堆if 这样的语句或硬编码一堆字符串,请停下来重新考虑一下你在做什么。几乎总是有一种更简单更好的方法。享受吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    相关资源
    最近更新 更多