Search code examples
iosswiftuitableviewswift3

How to recognize .delete in editingStyle in Swift 3 to delete cell in tableview


this all my func that connected to my table view. Why I can't delete row?

I also do in viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    self.myTableView.dataSource = self
    self.myTableView.delegate = self
    self.myTableView.reloadData()
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "incTV")

    cell.textLabel?.text = "X"

    cell.detailTextLabel?.text =  "Y"

    return cell
}


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

        myTableView.deleteRows(at: [indexPath], with: .fade)
        arr.remove(at: (indexPath as NSIndexPath).row)
        self.myTableView.reloadData()
    }
}

override func viewWillAppear(_ animated: Bool) {
    myTableView.reloadData()
}

Solution

  • First make sure your table has a delegate set, and that your delegate method is in the delegate class/controller.

    Second, try to use canEditRowAtIndexPath method and return true.