user8894520
user8894520

Reputation:

Not able to delete row at an indexpath

I have some tableview cells with some data on them and the cells have a cross button on them (at the top right) on the click of which the cell should get deleted. This is how I'm trying to delete...

extension sellTableViewController: imageDelegate {
    func delete(cell: sellTableViewCell) {
        if let indexPath = tableview?.indexPath(for: cell) {
            //1.Delete photo from datasource
            arrProduct?.remove(at: indexPath.row)
            print(self.appDelegate.commonArrForselectedItems)

            tableview.deleteRows(at: [indexPath], with: .fade)

        }
    }
}

But when I click on the cross button I get an error message saying The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

My tableview numberOfSections and numberOfRowsInSection is given as follows...

    func numberOfSections(in tableView: UITableView) -> Int {
        return (arrProduct?.count)!

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let product = arrProduct![section]

        return product.images.count
    }

Hope somebody can help...

Upvotes: 1

Views: 866

Answers (2)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16446

You are removing item from array at from indexPath.row but your array contains sections not rows

Just one line mistake replace

        arrProduct?.remove(at: indexPath.row)

With

        arrProduct?.remove(at: indexPath.section)

Hope it is helpful to you

EDIT

I think you are removing image from array then

arrProduct![indexPath.section].images.remove(at: indexPath.row)

Upvotes: 2

Gary Makin
Gary Makin

Reputation: 3169

Your code is confusing sections and rows. You are saying the number of sections is based on the number of products (arrProduct?.count) and the number of row is based on the number of images in the product for the section (arrProduct![section].images.count).

But in your delete function, you delete a product (arrProduct?.remove(at: indexPath.row)), which corresponds to a section but then you delete a row on the table.

Make sure you are clear when you are working with products (sections) and images (rows).

Upvotes: 0

Related Questions