UIButton with multiple target actions for same event

淺唱寂寞╮ 提交于 2020-05-30 08:23:45

问题


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:


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.



来源:https://stackoverflow.com/questions/56244140/uibutton-with-multiple-target-actions-for-same-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!