如何以编程方式假冒触摸事件到UIButton? [英] how to programmatically fake a touch event to a UIButton?

查看:94
本文介绍了如何以编程方式假冒触摸事件到UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些单元测试,并且由于这个特定应用程序的性质,我必须尽可能高地获得 UI 链。所以,我想要做的是以编程方式触发按钮按下,就像用户按下 GUI中的按钮一样。

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.

(是的,是的 - 我可以只是调用 IBAction 选择器,但同样,这个特定应用程序的性质重要的是我伪造实际按钮按下,这样就可以从按钮本身调用 IBAction 。)

(Yes, yes -- I could just 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.)

这样做的首选方法是什么?

What's the preferred method of doing this?

推荐答案

事实证明

[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];

在这种情况下,我得到了我所需要的。

got me exactly what I needed, in this case.

编辑:不要忘记在主线程中执行此操作,以获得类似于用户按下的结果。

Don't forget to do this in the main thread, to get results similar to a user-press.

对于Swift 3:

buttonObj.sendActions(for: .touchUpInside)

这篇关于如何以编程方式假冒触摸事件到UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆