0

I have a Navigation controller and I'm trying to put a button on the right of navigation bar but I can't handle the tap action. I'm declaring the UIBarButtonItem like this

let navigationButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(RestaurantsListViewController.logoutAction))

I'm adding the button on the viewDidLoad func

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = navigationButton
}

and the function that I'm trying to use to handle the tap event is this

func logoutAction(sender: AnyObject?){
    print("Logout")
}

but when I press the button, the message is not printed in console.

Dani Garcia
  • 464
  • 1
  • 6
  • 18

3 Answers3

3

Try this:

override func viewDidLoad() {
     super.viewDidLoad()

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ButtonName", style: .done, target: self, action: #selector(YourViewController.yourAction))

}
Mannopson
  • 2,634
  • 1
  • 16
  • 32
0
  let okbtn = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.logoutAction))

Try This otherwise You need to replace func like

func logoutAction()
{
  print("logout")
}
Sagar vaishnav
  • 97
  • 1
  • 1
  • 7
0

The issue here is when you create navigationButton as a class property, it gets initialized before self is initialized. So self doesn't exist yet when you pass it in as the target of the button.

There are a couple ways to fix it, including the answer by @Mannopson where you initialize the button inside the viewDidLoad, which ensures that self has already been created.

Another way to solve this issue is to declare navigationButton to be a lazy var:

lazy var navigationButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(RestaurantsListViewController.logoutAction))

The lazy var ensures that the property only gets initialized when the property gets accessed (hence it being a lazy initialization). Since the first time it is accessed happens in viewDidLoad, we can also be sure that self has been created. Hope this gives you more context!

kbunarjo
  • 1,277
  • 2
  • 11
  • 27