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!
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With