How can I send UILongPressGesture programmatically?

How to send a message to a UILongPressGesture object?

I know how to send touches, but not gestures. For example, if I wanted to send a message, I could use:

 [button sendActionsForControlEvents: UIControlEventTouchUpInside]; 

and the button will get a β€œtouch inside." I need to do the same with a long press gesture.

Consider automatically testing the user interface. Calling a selector associated with a gesture will not meaningfully verify anything.

+5
source share
2 answers

Import <UIKit/UIGestureRecognizerSubclass.h> and manually set the state property according to the sequence of states that you want to simulate. This will cause the added target / action pairs to be called. After each manual state, you must run a run loop to send messages.

For UILongPressGestureRecognizer , to get the correct sequence of states found in the actual gesture sequence "touch, hold, drag, release", I wrote the following code in a subclass of UIViewController inside viewDidLoad :.

 UILongPressGestureRecognizer *r = [[UILongPressGestureRecognizer alloc] init]; [self.view addGestureRecognizer:r]; [r addTarget:self action:@selector(recognize:)]; r.state = UIGestureRecognizerStateBegan; [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; r.state = UIGestureRecognizerStateChanged; [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; r.state = UIGestureRecognizerStateEnded; [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; [r reset]; 

I believe that this would be risky in the production code (you may wish to call reset later, but I did not find the difference between doing this or not in my testing), but if your use case is automatic testing to make sure goals and actions were set correctly, it can satisfy your needs.

+7
source

Do you know which selector is bound to its UILongPressGestureRecognizer ? If you knew this, you could just call. If you ask if there is a way, for example touchesMoved:(UITouch *)touch , then the answer is No.

0
source

Source: https://habr.com/ru/post/989233/


All Articles