Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a cell from tableView with animation through IBAction? iOS Swift 3.0

I'm building a todo-list app, and I'm holding a task model array and tableView in my view controller.

Each cell in this tableView contains several UI elements, one of them is a UIView that is actually a checkbox, implemented by Skyscanner's pod: https://github.com/Marxon13/M13Checkbox

I would like to remove a cell when a user tap on the checkbox (with animation).

I set an IBAction to the UIView, I know which element in the array I want to remove (I tagged each UIView) but I cannot use the method

tableView.deleteRows(at: [IndexPath], with: UITableViewRowAnimation)

since I don't have the index path. I want to find a nice way to remove the cell with an index, preferably without holding an indexPath variable (I tried that but not sure how to implement it correctly since cells can be removed from various indexes).

Thanks for your help!

like image 260
Bar Malka Avatar asked Dec 24 '22 15:12

Bar Malka


2 Answers

Thanks for everyone that helped! I'm answering my own question because it was a combination of your answers!

as Puneet Sharma, Reinier Melian and Yun CHEN said, I managed to create an index path inside the function. Puneet's comment is very important, you must remove the element from the array before you remove the cell.

PS. Maybe I could create the IndexPath way before I even asked the question, but in the line

self.tableView.deleteRows(at: [IndexPath(row: checkbox.tag, section: 0)], with: .automatic)

Xcode does not auto complete this initialization at all.

This is the code that remove the cell just like I wanted:

       @IBAction func completeBtnPressed(_ sender: Any) {
    let checkbox = (sender as! M13Checkbox)
    self.tasks.remove(at: checkbox.tag)

    self.tableView.deleteRows(at: [IndexPath(row: checkbox.tag, section: 0)], with: .automatic)
}

Thanks a lot!

like image 197
Bar Malka Avatar answered Dec 26 '22 11:12

Bar Malka


Set the action event on the checkbox/Button like bellow in cellForRowatIndexPath. don't forgot to add the tag on every checkbox/Button.

cell.btnCounter.tag = indexPath.row
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

You need to handle event as below

func buttonClicked(_ sender: UIButton) {
        //Here sender.tag will give you the tapped checkbox/Button index from the cell
        your_array.remove(at: sender.tag) //Remove your element from array
        tableView.deleteRows(at: [IndexPath(row: sender.tag, section: 0))], with: .automatic) //Hope it is in section 0
    }

Hope this help you

like image 31
Maulik Pandya Avatar answered Dec 26 '22 12:12

Maulik Pandya