alias235 alias235 - 1 year ago 266
Swift Question

Swift: Edit Mode, link editButtonItem() to IB Action

I understand how to set my

into edit mode, and how to dynamically create an edit button:

override func viewDidLoad(){
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(false, animated: false)
navigationItem.leftBarButtonItem = editButtonItem()

But when I tap the edit button, I would like a new button to appear on the navigation bar (i.e. a 'plus'/'add' button). To do this I think I need to create an
, but I don't know how to link the
to an action. Any ideas?

Answer Source

Ok, big thanks to Ahmed and vadian for their comments, but what I got working was this:

override func setEditing(editing: Bool, animated: Bool) {
    // Toggles the edit button state
    super.setEditing(editing, animated: animated)
    // Toggles the actual editing actions appearing on a table view
    tableView.setEditing(editing, animated: true)

    if (self.editing) {
        navigationItem.rightBarButtonItem =
            UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                            action: #selector(clickMe))

    } else {
        // we're not in edit mode 
        let newButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: navigationController, action: nil)
        navigationItem.rightBarButtonItem = newButton


func clickMe()
    print("Button Clicked")

As the edit button is pressed (and flips from Edit -> Done and back again) the code in the IF/ELSE statements will execute.