Rorschach Rorschach - 5 months ago 7x
Swift Question

pass a UIButton into a function

I have a function that runs when a button is pressed.

Inside that function is another function.

I would like to pass the pressed button into the inner function so that I can change the text of the button depending on stuff in that inner function.

@IBAction func newItem(sender: AnyObject) {
let urlFetch:String = urlField.text!
self.service.createNewItem(urlFetch, I_WANT_BUTTON_HERE)

How do I pass the button into the function?

If it helps this is the function that I am passing it to:

func createNewItem(item_url: String, plus_button: UIButton) {
let dataDictionary = ["url" : item_url]"item/create", data: dataDictionary).responseJSON { (response) -> Void in
plus_button.titleLabel!.text = "success"


Later I will add an if statement that changes the text depending on what the response is.


The object passed into newItem method is actually the button you tapped so you can securely convert the type of parameter sender into UIButton like below:

@IBAction func newItem(sender: UIButton) {
  self.service.createNewItem(urlFetch, sender)

There is also one thing though. Setting the text of titleLabel is not the right way of updating the title of button. You should be using setTitle:forState instead:

func createNewItem(item_url: String, plus_button: UIButton) {
  plus_button.setTitle("success", forState: .Normal)