Meet Shah Meet Shah - 4 months ago 10
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)
{
print("Tapped")
}

}


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

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) {
        print("tapped")
    }
}

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

Comments