how to programmatically fake a touch event to a UI

2019-01-07 02:29发布

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.

(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?

6条回答
孤傲高冷的网名
2楼-- · 2019-01-07 03:00

For Xamarin iOS

btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);

Reference

查看更多
做个烂人
3楼-- · 2019-01-07 03:03

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:

buttonObj.sendActions(for: .touchUpInside)

查看更多
Animai°情兽
4楼-- · 2019-01-07 03:05

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.

查看更多
狗以群分
5楼-- · 2019-01-07 03:13

An update to this answer for Swift

buttonObj.sendActionsForControlEvents(.TouchUpInside)

EDIT: Updated for Swift 3

buttonObj.sendActions(for: .touchUpInside)
查看更多
爷的心禁止访问
6楼-- · 2019-01-07 03:13

In this case, UIButton is derived from UIControl. This works for object derived from UIControl.

I wanted to reuse "UIBarButtonItem" action on specific use case. Here, UIBarButtonItem doesn't offer method sendActionsForControlEvents:

But luckily, UIBarButtonItem has properties for target & action.

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

Here, rightBarButtonItem is of type UIBarButtonItem.

查看更多
Juvenile、少年°
7楼-- · 2019-01-07 03:18

Swift 3:

self.btn.sendActions(for: .touchUpInside)
查看更多
登录 后发表回答