0

我应该在主视图中管理两个不同的视图;我想检测我的视图中手指的确切数量,也就是说,如果我在“第一个视图”中有四个手指,我想要一个 var 说我的值 = 4,如果我在“第二个视图”中有 3 个手指,我想要另一个var 说我的值 = 3。我向您展示我的代码不能正常工作。

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

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    NSLog(@"cgpoint:%f,%f", touchLocation.x, touchLocation.y);

    if (CGRectContainsPoint(view1.frame, touchLocation)){

        NSLog(@"TOUCH VIEW 1");
        totalTouch1 = [[event allTouches]count];
        NSLog(@"TOTAL TOUCH 1:%d", totalTouch1); 
    }

    else if (CGRectContainsPoint(view2.frame, touchLocation)){

        NSLog(@"TOUCH VIEW 2");
        totalTouch2 = [[event allTouches]count];
        NSLog(@"TOTAL TOUCH 2:%d", totalTouch2);
     }
 }

使用我的代码,如果我开始将手指放在“第一个视图”中,一切都可以,但是例如,如果我将无名指放在第二个视图中,我的代码会进入第一个“如果”并说我的手指还处于第一个视图中. 我不明白这个问题。

4

1 回答 1

0

[[event allTouches] anyObject];只为您带来其中一种触感。

你需要像这样迭代所有的触摸:

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

    int touch1 = 0;
    int touch2 = 0;
    NSArray *touches = [[event allTouches] allObjects];
    for( UITouch *touch in touches ) {
        CGPoint touchLocation = [touch locationInView:self.view];

        NSLog(@"cgpoint:%f,%f", touchLocation.x, touchLocation.y);

        if (CGRectContainsPoint(view1.frame, touchLocation)){

            NSLog(@"TOUCH VIEW 1");
            touch1 += 1;
            NSLog(@"TOTAL TOUCH 1:%d", totalTouch1);
        }

        else if (CGRectContainsPoint(view2.frame, touchLocation)){

            NSLog(@"TOUCH VIEW 2");
            touch2 += 1;
            NSLog(@"TOTAL TOUCH 2:%d", totalTouch2);
        }
    }

    NSLog(@"Total touches on view 1: %d", touch1);
    NSLog(@"Total touches on view 2: %d", touch2);
}
于 2013-04-12T14:38:05.170 回答