Search code examples
iosswiftuitableviewdelete-row

Swipe to delete without confirmation on UITableview


I have a tableview with realtime data using websocket. The Table view refresh the cell(or row) every two seconds.

I want to implement the feature swipe to delete (Without showing delete button) because every two seconds i call the reload rows that time trying to delete particular row the table view alignment collapsed. Can any one help on this?


Solution

  • You can add the UISwipeGestureRecognizer to your TableViewCell to do it.

    For example

    let swipeToDeleteGesture = UISwipeGestureRecognizer(target: self, action: #selector(deleteCellWithoutConfirm(gesture:)))
    swipeToDeleteGesture.direction = .left
    your_cell.addGestureRecognizer(swipeToDeleteGesture)
    

    and process the delete function

    @objc func deleteCellWithoutConfirm(gesture: UIGestureRecognizer) {
        guard let cell = gesture.view as? UITableViewCell,
            let indexPath = tableView.indexPath(for: cell) else {
            return
        }
        // delete your data first, then reload tableView
        your_data.remove(at: indexPath.row)
        tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
    }