Swipe Deletion of Table View Cells in UITableView with Swift

October 20, 2017

In this example I am going to show you how to delete table row with swipe in iOS devices

Now I am going to delete row from the following table

If you are not familiar with UITableView you see this article to study how to develop UITableView with data

We have the following code already from above example

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var days: [String] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.days.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = self.days[indexPath.row]
        return cell
    }
    

}

So now we will add the code to delete row

So what you have to do is implement the tableView:editingStyleForRowAtIndexPath: selector in the delegate and the tableView:commit editingStyle:forRowAtIndexPath: selector in the data source of your table view:

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete{
            print("Deleted Row")
            days.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .left)
        }
    }

You can run the application now and click where you want to start and hold down the mouse button and move the mouse slowly in the direction of the swipe and then release the mouse button
Now you can see the following screen

Now touch on the Delete button to delete the row