Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

ios - How can I send a UILongPressGesture programmatically?

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 use:

[button sendActionsForControlEvents: UIControlEventTouchUpInside];

and the button would receive a "touch up inside". I need to do the same thing with a long press gesture.

Think automated UI testing. Calling a selector associated with the gesture wouldn't meaningfully test anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...