滑动删除,当你滑动任何一个时删除列表中的第一个项目

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

每次我在 table 视图中滑动项目并删除它时,它会删除列表中的第一个项目,而不是我滑动的项目。我尝试了不同的方法,但仍然在做同样的事情

这是我的视图控制器函数,我在其中滑动并调用删除方法。

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

还有我的删除功能:

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

    }

预期结果是从列表中删除项目

你应该使用

indexPath.row

获取要对其执行操作的行的实际索引。

只需更新您的 modifyAction 代码:(在获取 ID 时添加 indexPath.row 而不是 0)

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