Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector not working on my swift UIBarButtonItem

I'm writing a to-do list type app, in order to learn swift for iOS development. I had a settings button on the Navigation bar, on the right side, and whenever a person clicked a button on top of the table view, they could add a new item to their list. That causes a "cancel" button to appear on the left side of the bar and a "add" button to appear on the right side. When the person is done, however, those buttons disappear, and so I programatically re-create the settings button, with a call to a function that is supposed to call the segue.

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "modify"), style: UIBarButtonItemStyle.Plain, target: nil, action: Selector("showSettings:"))

This is the code that creates the button on the navbar (and it is indeed created)

 func showSettings(sender: AnyObject?) {
    print("segueShouldBeDone!")
    performSegueWithIdentifier("showSettings", sender: sender)
}

And this is the function that is supposed to call the segue (I added the print to see if it was at least being called, and it isn't).

I've had this same problem in another place in my code, but I had given up on fixing it cause it wasn't that important for me then. But now it is interfering with how the app works, so I wanted to know how to fix it.

Any help would be great.

like image 516
AugustoQ Avatar asked Sep 26 '15 20:09

AugustoQ


1 Answers

Your showSettings: selector isn't being called because you specified nil instead of self for the bar button item's target. Change the line to:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "modify"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showSettings:"))

This assume the showSettings: method is in the same class that contains this line of code.

Read the documentation for this initializer, specifically the info about the target parameter.

like image 63
rmaddy Avatar answered Nov 14 '22 11:11

rmaddy