我发现 Apple 的UIGestureRecognizer设计非常好且可扩展。
这个想法是解耦手势(或交互)的识别和将被触发的动作。
您需要实现一个基本或抽象的 GestureRecognizer 类,该类能够基于事件 MousePressEvent、MouseReleaseEvent、MouseMoveEvent 或 MouseWheelEvent 等识别特定交互或手势。 GestureRecongnizers 具有定期报告更改的目标。
例如,您非常基本的课程就像:(对不起,我可怜的半 C++ 伪代码......最近我不怎么用它)
class Recognizer {
int state; // ex: 0:possible, 1:began, 2:changed, 3:ended/recognized 4:cancelled
protected:
void setTarget(void &theTarget); // or even better a touple, target/method. In this case target is assumed to have a method gestureHandle(Recognizer *r);
virtual void mouserPress() = 0;
virtual void mouserRelease() = 0;
virtual void mouserMove() = 0;
virtual void mouserWheel() = 0;
...
}
如果您想检测鼠标滑动
class SwipeRecognizer : Recognizer {
int direction; // ex: 0:left2right 1:bottom2top 2:...
private:
void mouserPress() {
state = 0; // possible. You don't know yet is the mouse is going to swipe, simple click, long press, etc.
// save some values so you can calculate the direction of the swipe later
target.gestureHandle(this);
};
void mouserMove() {
if (state == 0) {
state = 1; // it was possible now you know the swipe began!
direction = ... // calculate the swipe direction here
} else if (state == 1 || state == 2) {// state is began or changed
state = 2; // changed ... which means is still mouse dragging
// probably you want to make more checks here like you are still swiping in the same direction you started, maybe velocity thresholds, if any of your conditions are not met you should cancel the gesture recognizer by setting its state to 4
}
target.gestureHandler(this);
};
void mouserRelease() {
if (state == 2) { // is swipping
state = 3; // swipe ended
} else {
state = 4; // it was not swiping so simple cancel the tracking
}
target.gestureHandler(this);
};
void mouserWheel() {
// if this method is called then this is definitely not a swipe right?
state = 4; // cancelled
target.gestureHandler(this);
}
只需确保在事件发生时调用上述方法,并且它们应该在需要时调用目标。
这就是目标对我的看法:
class Target {
...
void gestureHandler(Recognizer *r) {
if (r->state == 2) {
// Is swipping: move the opengl camera using some parameter your recognizer class brings
} else if (r->state == 3) {
// ended: stop moving the opengl camera
} else if (r->state == 4) {
// Cancelled, maybe restore camera to original position?
}
}
UIGestureRecognizer 的实现非常好,将允许为同一个识别器注册多个目标/方法,并将多个识别器注册到同一个视图。UIGestureRecognizers 有一个委托对象,用于获取有关其他手势识别器的信息,例如,是否可以同时检测到两个手势,或者一旦检测到另一个手势就必须失败,等等。
某些手势识别器将需要比其他手势识别器更多的覆盖,但最大的优点是它们的输出是相同的:通知当前状态(和其他信息)的处理程序方法。
我认为值得一看
希望能帮助到你 :)