lascoff
lascoff

Reputation: 1331

Swift Navigation Bar item not calling action

I have an item on the navigation bar that calls an action. It stopped working. I have disconnected the item from the action and re-attached. Still no action. The action is attached in the storyboard. How do I debug or solve this issue?

Upvotes: 6

Views: 5393

Answers (3)

asilturk
asilturk

Reputation: 218

The key point is the target parameter, in your issue.

If you don't set target: self, you have no chance to know the method that you called from your class will work or not. The selector method you wanna trigger will behave strangely, sometimes it will work, sometimes not.

You have to set the self attribute to your target parameter. Not nil.

Example usage in code:

// trigger func, used from #selector
@objc func selectorMethod() { /*...*/ }

// create the button you wanna set
let rightButton = UIBarButtonItem(title: "ButtonTitle", style: .plain, target: self, action: #selector(selectorMethod))

// set the button item to the right bar
navigationItem.rightBarButtonItem = rightButton 

Upvotes: 0

Mannopson
Mannopson

Reputation: 2684

Try something like this

If you have a parameter

 override func viewDidLoad() {
    super.viewDidLoad()

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

}

Without parameter

 override func viewDidLoad() {
    super.viewDidLoad()

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

}

Upvotes: 6

Roman Sheydvasser
Roman Sheydvasser

Reputation: 193

If you used the drag and drop functionality for creating the IBAction method, make sure it created the method for the button and not the "Bar Button Item."

The easiest way to check is by opening the Document Outline view in your Storyboard.

Upvotes: 1

Related Questions