Can I add multiple target actions on a UIButton for the same event like below?
[button addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:object action:@selector(yyy) forControlEvents:UIControlEventTouchUpInside];
I made a quick app to test it out and it carries out both the actions on button press.
I want to know if it's good practice to do so, and also will the order of execution always remain the same?
Thanks in advance.
Edit: I did find this post which states it's called in reverse order of addition, i.e., the most recently added target is called first. But it's not confirmed
Yes it is possible to add multiple actions to a button.
personally i would prefer a Delegate to subscribe to the button.
Let the object
you want to add as target
subscribe on the delegate's method so it can receive events when you press the button.
or
A single action that forwards the event to other methods to be fully in control
A simple test in swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let button = UIButton(frame: CGRect(x: 50, y: 50, width: 300, height: 30))
button.backgroundColor = .orange
button.addTarget(self, action: #selector(action1), for: .touchUpInside)
button.addTarget(self, action: #selector(action2), for: .touchUpInside)
button.addTarget(self, action: #selector(actionHandler), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func actionHandler(_ sender: UIButton){
print("actionHandler")
action1(sender)
action2(sender)
}
@objc func action1(_ sender: UIButton) {
print("action1")
}
@objc func action2(_ sender: UIButton) {
print("action2 \n")
}
}
Output after one click:
action1
action2
actionHandler
action1
action2
Can you confirm on the order of execution when normally adding the actions
Yes it is executed in the order you set the targets.
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