Pregunta

I should manage two different views inside my main view; I want detect the exact number of finger inside my views, that is if I have four fingers inside "first view" I want a var that say me a value = 4, and if I have 3 fingers in "second view" I want another var that say me a value = 3. I show you my code that don't work fine.

- (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);
     }
 }

With my code if I begin to lay my finger in "first view", it's all ok, but for example if I lay my fourth finger inside second view my code enter in first "if" and say that my finger is yet in first view. I don't understand the problem.

¿Fue útil?

Solución

[[event allTouches] anyObject]; is fetching you only one of the touches.

you need to iterate over all the touches like so:

- (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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top