How can I send a UILongPressGesture programmatically?

前端 未结 2 1502
抹茶落季
抹茶落季 2020-12-10 08:05

How can I send a UILongPressGesture message to an object?

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

相关标签:
2条回答
  • 2020-12-10 08:26

    Import <UIKit/UIGestureRecognizerSubclass.h> and manually set the state property as appropriate to the sequence of states you need to simulate. This will cause the added target/action pairs to be called. After each time manually setting the state, you must let the run loop run in order for the messages to be dispatched.

    For the UILongPressGestureRecognizer, to get the correct sequence of states as is found in an actual, 'touch, hold, drag, release' sequence of gestures, I wrote the following code in a UIViewController subclass 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 imagine this would be risky in production code (you may wish afterwards to call reset but I found no difference between doing so or not in my testing), but if your use case is automated testing to verify that the targets and actions have been set correctly this may meet your needs.

    0 讨论(0)
  • 2020-12-10 08:49

    Do you know what selector the object has tied to its UILongPressGestureRecognizer? If you knew that, you could just call it. If you're asking if there's a method like touchesMoved:(UITouch *)touch, then the answer's no.

    0 讨论(0)
提交回复
热议问题