How to attach custom actions to an Edit Button Item (or The Dark Secrets of the Edit/Done Button)

You can create an editButtonItem in a UITableViewController like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
}

If your view controller is embedded into a navigation controller, an edit/done button will show up and you can toggle its state by pressing it.

Edit-Done

That’s great, but it takes a deeper understanding of how this happens to make full use of it in your own projects.

What this button actually does is set the “editing” property of your view controller to YES or NO. If it’s YES, the button turns into “Done” (and equivalent translations), and if it’s NO then it turns into “Edit”. You won’t notice this on a standard view controller, but on derivatives (such as a UITableViewController) this has a substantial effect: the table view enters edit mode and changes appearance.

You can therefore test the state of the button by querying your view controller:

    if (self.editing) {
        // we're in edit mode
        
    } else {
        // we're not in edit mode
        
    }

But that’s not an action, that’s just a test. If you’d like for something to happen when that edit button is pressed, you must override the following function which is called every time that button is pressed:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    
    // overriding this method means we can attach custom functions to the button
    [super setEditing:editing animated:animated];
    
    // attaching custom actions here
    if (editing) {
        // we're in edit mode
        
    } else {
        // we're not in edit mode
        
    }
}

This method is called by the table view when that button is pressed. We’re calling the super method first, then add our own bits at the end. You can also call this method from anywhere and put the table view into or out of edit mode like so:

[self setEditing:NO animated:YES];




Leave a Reply