2

所以我正在做自定义手势识别,我遇到了麻烦。我需要监控所有当前的触摸,但是, 和touchesBeganalltouchesEnded只给我他们正在监控的触摸。我需要对所有的触摸进行计算,不管它们是否被监控。我已经进行了一些研究,并看到了自己监控触摸的建议,但对我来说并不顺利。这是我的代码:touchesMovedtouchesCancelled

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    [myTouches unionSet:touches];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    NSArray *objects = [myTouches allObjects];

    for (UITouch *touch in touches) {
        for (UITouch *touch2 in objects) {
            if (CGPointEqualToPoint([touch2 locationInView:self.view], [touch previousLocationInView:self.view])) {
                [myTouches removeObject:touch2];
                [myTouches addObject:touch];
            }
        }
    }
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [myTouches minusSet:touches];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    [myTouches minusSet:touches];

    NSArray *objects = [myTouches allObjects];

    for (UITouch *touch in touches) {
        for (UITouch *touch2 in objects) {
            if (CGPointEqualToPoint([touch2 locationInView:self.view], [touch previousLocationInView:self.view])) {
                [myTouches removeObject:touch2];
            }
        }
    }
}

我想要的:myTouches应该是屏幕上所有触摸的准确表示。我得到的是:myTouches不断增长,尽管有时来自事件的触摸被正确注册为与myTouches. 我还做了一个测试,我用一个整数计算注册的触摸次数touchesBegan并减去注册的触摸touchesEnded次数,结果总是为正数,这意味着注册的触摸次数多于结束的次数。请帮忙!

4

1 回答 1

1

尝试 UIApplication 的子类来监控应用程序中的所有触摸。

    @interface MyUIApplication : UIApplication

然后使用sendEvent事件MyUIApplication

    - (void)sendEvent:(UIEvent *)event {

        [super sendEvent:event];
        NSSet *allTouches = [event allTouches];
        if ([allTouches count] > 0) {

             //To get phase of a touch
             UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
             if (phase == UITouchPhaseBegan){

                 //Do the stuff
             }
             //also you can use UITouchPhaseMoved, UITouchPhaseEnded,
             // UITouchPhaseCancelled and UITouchPhaseStationary
        }
    }

并且不要忘记在 main 中添加类

    int main(int argc, char *argv[])
    {
          @autoreleasepool {
                return UIApplicationMain(argc, argv, NSStringFromClass([MyUIApplication class]), NSStringFromClass([AppDelegate class]));
          }
    }
于 2013-12-31T11:56:31.693 回答