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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With