Meet Shah Meet Shah - 3 months ago 9
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.


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.