Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override action method for UIButton in Swift?

I have one UIButton. I want to use the same UIButton to execute multiple actions. First I'm setting the action to a button programmatically.

button1.addTarget(self, action: #selector(ViewController.function1), forControlEvents: .TouchUpInside)

Next, I want to discard that funtion and want to add other action.

button1.addTarget(self, action: #selector(ViewController.function2), forControlEvents: .TouchUpInside)

Is it possible to override existing target for button?

like image 462
chandra mohan Avatar asked Jul 04 '16 14:07

chandra mohan


2 Answers

The case you suggested wont override the previous action but add the second action to the button resulting in ViewController.function1 and ViewController.function2 being called.

You need to remove the previous action from target before adding new one by using

button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents)

Or remove all the previous actions before adding the new one

button1.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

like image 129
Sharath Shenoy P Avatar answered Nov 15 '22 19:11

Sharath Shenoy P


You need to remove the previous action from target before adding new one else it will cause both the actions to trigger

button1.removeTarget(self, action: #selector(ViewController.function1), forControlEvents: .AllEvents)
like image 33
Rohit Pradhan Avatar answered Nov 15 '22 18:11

Rohit Pradhan