ios 如何以编程方式将触摸事件伪造为 UIButton?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4028734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to programmatically fake a touch event to a UIButton?
提问by Olie
I'm writing some unit tests and, because of the nature of this particular app, it's important that I get as high up the UI
chain as possible. So, what I'd like to do is programmatically trigger a button-press, as if the user had pressed the button in the GUI
.
我正在编写一些单元测试,并且由于这个特定应用程序的性质,我尽可能地在UI
链上处于高位非常重要。所以,我想做的是以编程方式触发按钮按下,就好像用户按下了GUI
.
(Yes, yes -- I couldjust call the IBAction
selector but, again, the nature of this particular app makes it important that I fake the actual button press, such that the IBAction
be called from the button, itself.)
(是的,是的——我可以只调用IBAction
选择器,但同样,这个特定应用程序的性质使得我伪造实际按钮按下很重要,这样就IBAction
可以从按钮本身调用。)
What's the preferred method of doing this?
这样做的首选方法是什么?
回答by Olie
It turns out that
事实证明
[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];
got me exactly what I needed, in this case.
在这种情况下,我得到了我需要的东西。
EDIT:Don't forget to do this in the main thread, to get results similar to a user-press.
编辑:不要忘了这样做在主线程,以获得类似于用户按下结果。
For Swift 3:
对于 Swift 3:
buttonObj.sendActions(for: .touchUpInside)
buttonObj.sendActions(for: .touchUpInside)
回答by Hellojeffy
An update to this answer for Swift
Swift 这个答案的更新
buttonObj.sendActionsForControlEvents(.TouchUpInside)
EDIT: Updated for Swift 3
编辑:为 Swift 3 更新
buttonObj.sendActions(for: .touchUpInside)
回答by Jeff Kelley
If you want to do this kind of testing, you'll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.
如果你想做这种测试,你会喜欢 iOS 4 中的 UI 自动化支持。你可以很容易地编写 JavaScript 来模拟按钮按下等,尽管文档(尤其是入门部分)有点疏。
回答by Hitesh Savaliya
In this case, UIButton
is derived from UIControl
. This works for object derived from UIControl
.
在这种情况下,UIButton
来自UIControl
。这适用于从UIControl
.
I wanted to reuse "UIBarButtonItem
" action on specific use case. Here, UIBarButtonItem
doesn't offer method sendActionsForControlEvents:
我想UIBarButtonItem
在特定用例上重用“ ”操作。这里,UIBarButtonItem
不提供方法sendActionsForControlEvents:
But luckily, UIBarButtonItem
has properties for target & action.
但幸运的是,UIBarButtonItem
具有目标和行动的属性。
if(notHappy){
SEL exit = self.navigationItem.rightBarButtonItem.action;
id world = self.navigationItem.rightBarButtonItem.target;
[world performSelector:exit];
}
Here, rightBarButtonItem
is of type UIBarButtonItem
.
这里,rightBarButtonItem
是 类型UIBarButtonItem
。
回答by Durai Amuthan.H
回答by Gobi M
Swift 3:
斯威夫特 3:
self.btn.sendActions(for: .touchUpInside)
回答by ELEMENTO Arts
Swift 4:
斯威夫特 4:
self .yourButton(self)
self .yourButton(self)