Meet Shah Meet Shah - 1 year ago 78
Swift Question

Need to add common UIBarButtonItem across all VCs

Following is piece of code which is not working:-

class Person {

static fun addBtn(cName:UIViewController)
let rightBtn = UIBarButtonItem.init(title: "Right", style: .Plain, target: UIBarButtonItem.self, action:#selector(UIBarButtonItem.self.newMenuTapped(_:)))
cName.navigationItem.rightBarButtonItem = rightBtn

extension UIBarButtonItem

func newMenuTapped(sender: UIBarButtonItem)


Issue : -
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: unrecognized selector sent to class 0x14c830

Can someone guide be as to what i am doing wrong. Thanks.

Answer Source

Create an extension for UIViewController like this:

extension UIViewController {
    func addButton() {
        let button = UIBarButtonItem(title: "Right", style: .Plain, target: self, action: #selector(self.rightButtonPressed(_:)))
        self.navigationItem.setRightBarButtonItem(button, animated: false)

    func rightButtonPressed(sender: UIBarButtonItem) {

And call self.addButton() in all view controllers where you want to implement the button.

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