ios - 具有针对同一事件的多个目标操作的 UIButton
问题描述
我可以在 UIButton 上为同一个事件添加多个目标操作,如下所示?
[button addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:object action:@selector(yyy) forControlEvents:UIControlEventTouchUpInside];
我做了一个快速应用程序来测试它,它执行按钮按下的两个动作。
我想知道这样做是否是一种好习惯,并且执行顺序是否始终保持不变?
提前致谢。
编辑:我确实找到了这篇文章,其中指出它是以相反的添加顺序调用的,即首先调用最近添加的目标。但是没有得到证实
解决方案
是的,可以向按钮添加多个操作。
就我个人而言,我更希望代表订阅该按钮。让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
正常添加动作时能否确认执行顺序
是的,它按照您设置目标的顺序执行。
推荐阅读
- elasticsearch - 具有多个必须和应该的嵌套布尔查询
- python - 检测文本和纠偏
- html - 如何在 cakephp 分页中设置自定义过滤器
- assembly - Mult.asm 比较失败
- ios - 多用户共享一台设备时使用指纹登录iOS应用程序
- database - 如何在 DolphinDB 中获取空值在向量中的位置?
- c# - 如何防止在大字符串的空白行中添加后缀?C#
- c++ - 引入 std::enable_if 后出现“不匹配”错误
- php - 如何在运行 php 脚本的 aws-lambda 函数中从客户端获取连接中止事件?
- c++ - 引用另一个类时的 istream 重载