1

I am trying to programatically add a UIBarButtonItem to my nav bar (which works), however I cannot get the action to work. What am I doing wrong?

I have the following code under viewDidLoad:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "visualise"), style: .plain, target: self, action: #selector(visualise(sender:)))

And the following function declared outside the VC class:

func visualise(sender: UIBarButtonItem) {
// stuff to do once the button is tapped
}

I read a few answers saying the function cannot be local but that did not seem to help.

2
  • 1
    The selector must be part of the class referenced by the target. Commented Jun 23, 2018 at 22:41
  • You also need @objc before the function, otherwise you get a compiler error that the function is not exposed to Objective-C Commented Mar 19, 2020 at 16:53

1 Answer 1

3

The function can not be “global”. That is what the error says.

If your function is declared outside the view controller then it is global.

You can only call instance (or static) functions from a selector.

The simplest change would be to put your function inside the view controller.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked like a charm, thanks a lot. What confused me was that I read someone saying it cannot be part of any class, so I thought I couldn't put it int he VC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.