how to programmatically fake a touch event to a UIButton?

Olie picture Olie · Oct 27, 2010 · Viewed 104.3k times · Source

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?

Answer

Olie picture Olie · Oct 27, 2010

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)