2

I´m trying to make a new custom navigation bar button with my own image. That´s working fine, but I´m trying to open a new view controller when I press that button. Unfortunately that doesn´t work and I have no idea how I should do it.

let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "Image.png"), style: .plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem  = testUIBarButtonItem
func clickButton(sender: UIBarButtonItem){}

That´s my code right now and its inside my viewDidLoad. My intention is to perform a show detail Segue comment. Can someone help me ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
tobias
  • 25
  • 1
  • 4

2 Answers2

1

why don't you just use a UIButton and assign it as bar button item as suggested in this thread:

UIBarButtonItem: target-action not working?

let button  = UIButton(type: .Custom)
if let image = UIImage(named:"icon-menu.png") {
    button.setImage(image, forState: .Normal)
}
button.frame = CGRectMake(0.0, 0.0, 30.0, 30.0)
button.addTarget(self, action: #selector(MyClass.myMethod), forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem(customView: button)
navigationItem.leftBarButtonItem = barButton
Objective D
  • 799
  • 5
  • 16
0

If you are using a Storyboard, add a manual segue to your ViewController and give it an identifier. Then you have to call performSegue in your custom navigationbar button's IBAction.

func clickButton(sender: UIBarButtonItem){
    self.performSegue(withIdentifier: "yourSegueIdentifier", sender: nil)
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • I´ve made a manual segue but it still won´t open the new view controller `let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "Image.png"), style: .plain, target: self, action: nil) self.navigationItem.rightBarButtonItem = testUIBarButtonItem func clickButton(sender: UIBarButtonItem){ self.performSegue(withIdentifier: "idPage3", sender: nil)}` – tobias Jul 23 '17 at 17:31
  • Do you get any errors? Is you IBAction even called? – Dávid Pásztor Jul 23 '17 at 19:03
  • I don´t get any errors and I really think that my action isn´t being called. Nothing happens wen I push that button. Do I have forgotten something ? Is it correct to have all in viewDidLoad ? – tobias Jul 23 '17 at 19:51
  • As I mentioned, have a look in this thread: https://stackoverflow.com/questions/2796438/uibarbuttonitem-target-action-not-working Try my example code from my answer above and assign the selector with your click button function. It will work. And yes, it is legit to have all this configuration set up in your `viewDidLoad` method. – Objective D Jul 23 '17 at 20:10
  • Thanks for the help! It works now. I had forgotten this paragraph in my code `action:#selector(Class.MethodName)` and all worked after I´ve moved my `fun clickButton`below my `viewDidLoad` – tobias Jul 23 '17 at 21:00