The*_*ist 3 objective-c uibutton ios
我可以在 UIButton 上为相同的事件添加多个目标操作,如下所示?
[button addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:object action:@selector(yyy) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)
我制作了一个快速的应用程序来测试它,它在按下按钮时执行两种操作。
我想知道这样做是否是好的做法,并且执行顺序是否始终保持不变?
提前致谢。
编辑:我确实找到了这篇文章,它指出它以相反的添加顺序调用,即首先调用最近添加的目标。但是没有得到证实
是的,可以向按钮添加多个操作。
我个人更喜欢代表订阅按钮。让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")
}
}
Run Code Online (Sandbox Code Playgroud)
一键输出:
action1
action2
actionHandler
action1
action2
Run Code Online (Sandbox Code Playgroud)
正常添加动作的时候能不能确认一下执行的顺序
是的,它是按照您设置的目标顺序执行的。
| 归档时间: |
|
| 查看次数: |
1902 次 |
| 最近记录: |