如何以编程方式假冒触摸事件到UIButton?

Oli*_*lie 181 iphone uibutton touch-event ios

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

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

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

Oli*_*lie 452

事实证明

[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我得到了我需要的东西.

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


对于Swift 3:

buttonObj.sendActions(for: .touchUpInside)

  • 你在评论回复中有很大的克制;) (11认同)
  • 不幸的是,这些都不会始终有效 - 它们依赖于接收器是UIControl,而不是例如具有轻击手势. (2认同)

Hel*_*ffy 50

对Swift的这个答案的更新

buttonObj.sendActionsForControlEvents(.TouchUpInside)
Run Code Online (Sandbox Code Playgroud)

编辑:更新为Swift 3

buttonObj.sendActions(for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)


Jef*_*ley 6

如果你想进行这种测试,你会喜欢iOS 4中的UI自动化支持.你可以很容易地编写JavaScript来模拟按键等,尽管文档(特别是入门部分)有点疏.

  • 我理解仪器,杰夫 - 我所说的是:我希望我的单元测试能够放在我口袋里的设备上,没有笔记本电脑或XCode或仪器.或者你知道在设备上运行仪器的秘诀吗?;) (6认同)

Hit*_*iya 5

在这种情况下,UIButton是源于UIControl.这适用于派生自的对象UIControl.

我想UIBarButtonItem在特定用例上重用" "操作.在这里,UIBarButtonItem不提供方法sendActionsForControlEvents:

但幸运的是,它UIBarButtonItem具有目标和行动的属性.

 if(notHappy){        
         SEL exit = self.navigationItem.rightBarButtonItem.action;
         id  world = self.navigationItem.rightBarButtonItem.target;
         [world performSelector:exit];
 }
Run Code Online (Sandbox Code Playgroud)

这里rightBarButtonItem是类型UIBarButtonItem.


Dur*_*n.H 5

对于 Xamarin iOS

btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
Run Code Online (Sandbox Code Playgroud)

参考


Gob*_*i M 5

斯威夫特3:

self.btn.sendActions(for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

  • 这只是重复得分较高的答案。 (2认同)