2

I understand how to set my UITableView 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 IBAction, but I don't know how to link the editButtonItem() to an action. Any ideas?

lukkea
  • 3,606
  • 2
  • 37
  • 51
alias235
  • 53
  • 6

2 Answers2

2

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.

alias235
  • 53
  • 6
1

You can replace the default action of editButtonItem() by assigning a new function defined in your view controller to its action property.

editButtonItem().action = #selector(yourCustomAction(_:))

func yourCustomAction(sender: UIBarButtonItem) {}
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
  • Thanks for your reply Ahmed, apologises, but what do you mean by '#selector'? – alias235 May 12 '16 at 13:02
  • refer to this answer to better understand swift selector: [http://stackoverflow.com/questions/24007650/selector-in-swift](http://stackoverflow.com/questions/24007650/selector-in-swift) and [https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3#.q25ftjr60](https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3#.q25ftjr60) – Ahmed Onawale May 12 '16 at 13:09
  • I wouldn't recommend this. This kills all of the built in functionality of the editButtonItem & it won't switch from "edit" to "done" on its own. Definitely override the setEditing method like @alias235 did – Trev14 Feb 03 '18 at 23:58