3
votes

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

1
Whether it's "a good practice to do so" is largely opinion based. The documentation makes no claims about the order so I wouldn't count on the order. In fact, I would assume the order of execution is random.rmaddy
If order is important, use a single action handler and in that handler execute the tasks in the desired order.liquid
@bsod that's a neat solution and I already thought of it, but how would I pass the target (other than self) and selector to the action handler?TheLinuxEvangelist

1 Answers

5
votes

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.