Ana
Ana

Reputation: 119

Delete on swipe, removes first item in the list when you swipe any one

Every time I swipe item in table view and delete it, it deletes the first item in the list, not the one I swipe. I tried different approaches but still doing the same

Here is my view controller function, where I swipe and call delete method.

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? 
{

let modifyAction = UIContextualAction(style: .normal, title: "Modify", handler:
        { ac, view, success in
            var stmt: OpaquePointer?

            let deleteStatementStirng = "SELECT * FROM ShoppingList"
            if sqlite3_prepare(self.db, deleteStatementStirng, -1, &stmt, nil) != SQLITE_OK
            {
                print("error preparing delete")
            }

            if sqlite3_step(stmt) == SQLITE_ROW {
                let id = sqlite3_column_int(stmt, 0)
                self.deleteRow(itemId: Int32(id))
            }
            success(true)
        }
    )

    modifyAction.backgroundColor = .red
    return UISwipeActionsConfiguration(actions: [modifyAction])
}

And also my delete function:

func deleteRow(itemId: Int32){
        let deleteStatementStirng = "DELETE FROM ShoppingList WHERE id = \(itemId)"

        var deleteStatement: OpaquePointer?

        if sqlite3_prepare(db, deleteStatementStirng, -1, &deleteStatement, nil) == SQLITE_OK{

            if sqlite3_step(deleteStatement) == SQLITE_DONE {
                print("Successfully deleted row.")
            } else {
                print("Could not delete row.")
            }
        } else {
            print("DELETE statement could not be prepared")
        }

        sqlite3_finalize(deleteStatement)
        readValues()

    }

Expected result is to delete item from the list

Upvotes: 0

Views: 81

Answers (2)

Mitesh Mistri
Mitesh Mistri

Reputation: 459

Just update your modifyAction code with: (Added indexPath.row instead 0 while getting id)

let modifyAction = UIContextualAction(style: .normal, title: "Modify", handler:
    { ac, view, success in
        var stmt: OpaquePointer?

        let deleteStatementStirng = "SELECT * FROM ShoppingList"
        if sqlite3_prepare(self.db, deleteStatementStirng, -1, &stmt, nil) != SQLITE_OK
        {
            print("error preparing delete")
        }

        if sqlite3_step(stmt) == SQLITE_ROW {
            let id = sqlite3_column_int(stmt, indexPath.row)
            self.deleteRow(itemId: Int32(id))
        }
        success(true)
    }
)

Upvotes: 1

Droid GEEK
Droid GEEK

Reputation: 192

You should use

indexPath.row

to get actual index of row that you want to perform action on.

Upvotes: 1

Related Questions