简体   繁体   English

从表视图中删除单元格后更新indexPath.row

[英]Updating indexPath.row after deleting a cell from table view

I have a table view with cells that present a different table view when tapped on, according to the indexPath, ie: 根据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)
}

However when I delete a cell like so.... 但是,当我删除像这样的单元格时...

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()
    }
}

....the indexPath isn't updated, so if I delete the Apple cell (at indexPath.row 0), the Google cell takes its place, but still leads to the Apple products page, and so on and so forth for the rest of the companies. .... indexPath不会更新,因此,如果我删除Apple单元格(位于indexPath.row 0),则Google单元格将取代其位置,但仍会转到Apple产品页面,依此类推等等。其他公司。 I figured the tableView.delete rows line was taking care of that, but it's not. 我认为tableView.delete rows行可以解决此问题,但事实并非如此。 How can I update the indexPath once something is deleted? 删除某些内容后,如何更新indexPath?

Don't hardcode data and assume specific rows. 不要对数据进行硬编码,并假设使用特定的行。 Put the data into an array and get the values from the array based on the index path. 将数据放入数组,然后根据索引路径从数组中获取值。 When a row is deleted, update your data model by deleting from the array. 删除行后,通过从数组中删除来更新数据模型。

Update your didSelectRow method to: 将您的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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM