Search code examples
iphonetouch

how to track multitouch events on iphone?


I would like to track the separate touch sequences from touchesBegan through touchesMoved up until the touchesEnded. I am getting the coordinates of single touch events, but I would like to know which touch event corresponds to which touch event sequence.

For instance, if I am moving a first finger across the screen, and then touch the screen with the second finger, and remove the first finger - I want to display the coordinates of the first finger in red color and the coordinates of second finger in blue color.

Is this possible? If yes, how do I determine which events should be "red" and which events should be "blue"?

This is my code:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self handleTouches:[event allTouches]];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self handleTouches:[event allTouches]];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self handleTouches:[event allTouches]];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self handleTouches:[event allTouches]];
}

- (BOOL)handleTouches: (NSSet*)touches {
    for (UITouch* touch in touches) {
        // ...
    }
}

Solution

  • The touch objects are consistent through the events, so if you wanted to track a red and a blue touches, you'd declare an iVar for each, when the touches start, you assign whichever touch you want to that ivar and then, in your loop, you would check if the touch is the same as the pointer you stored.

    UITouch *red;
    UITouch *blue;
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        for (UITouch* touch in touches) {
            if(something) red = touch;
            else blue = touch;
        }
    }
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        [self handleTouches:touches];
    }
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        for (UITouch* touch in touches) {
            if(red == touch) red = nil;
            if(blue == touch) blue = nil;
        }
    }
    -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
        for (UITouch* touch in touches) {
            if(red == touch) red = nil;
            if(blue == touch) blue = nil;
        }
    }
    
    - (BOOL)handleTouches: (NSSet*)touches {
        for (UITouch* touch in touches) {
            if(red == touch) //Do something
            if(blue == touch) //Do something else
        }
    }