Rorschach
Rorschach

Reputation: 3802

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]

    self.post("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.

Upvotes: 0

Views: 1294

Answers (2)

iOS Geek
iOS Geek

Reputation: 4855

Instead of sending AnyObject as parameter in the newItem function, pass a UIButton.

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

Upvotes: 2

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

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)
}

Upvotes: 2

Related Questions