Edmund Edmund - 1 year ago 133
Swift Question

Swift: How to enter edit mode for table?

I have a RootViewController that embeds a container that contains a table:

enter image description here

I'd like the garbage can icon on the top left of the RootViewController to enable editing mode for the embedded table view. I would like them to show up as checkboxes so that I can select multiple rows at once and then press "Delete" to delete all of the selected ones.

How would I do this?

Answer Source

Hopefully your class already conforms to UITableViewDelegate like so:

class MyViewController: UIViewController, UITableViewDelegate

In viewDidLoad(), you would need to have:

myTable.delegate = self

Then you can hook up the trash can icon to an IBAction that sets the table to editing mode:

@IBAction func myTableSetEditing(sender: AnyObject) {        
    myTable.setEditing(true, animated: true)   

Then, as we see in an answer here: Select multiple rows in tableview and tick the selected ones, in viewDidLoad() put:

self.tableView.allowsMultipleSelection = true

and to get your checkmark, implement:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None

That takes care of the first half of your question and hopefully leads you to gaining insight and implementing some of your own logic for the rest of it. Cheers!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download