d0xi45
d0xi45

Reputation: 155

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, i.e.:

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. I figured the tableView.delete rows line was taking care of that, but it's not. How can I update the indexPath once something is deleted?

Upvotes: 1

Views: 1048

Answers (1)

rmaddy
rmaddy

Reputation: 318944

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:

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

Upvotes: 2

Related Questions