首页 > 解决方案 > 具有针对同一事件的多个目标操作的 UIButton

问题描述

我可以在 UIButton 上为同一个事件添加多个目标操作,如下所示?

[button addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:object action:@selector(yyy) forControlEvents:UIControlEventTouchUpInside];

我做了一个快速应用程序来测试它,它执行按钮按下的两个动作。

我想知道这样做是否是一种好习惯,并且执行顺序是否始终保持不变?

提前致谢。

编辑:我确实找到了这篇文章,其中指出它是以相反的添加顺序调用的,即首先调用最近添加的目标。但是没有得到证实

标签: iosobjective-cuibutton

解决方案


是的,可以向按钮添加多个操作。

就我个人而言,我更希望代表订阅该按钮。让object您想要添加为target委托方法的订阅,以便在您按下按钮时它可以接收事件。

或者

将事件转发给其他方法以完全控制的单个操作

一个简单的快速测试

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")
  }
}

一键输出:

action1
action2 

actionHandler
action1
action2 

正常添加动作时能否确认执行顺序

是的,它按照您设置目标的顺序执行。


推荐阅读