Search code examples
iphonexcodetouchtouches

iPhone: How can I detect which touch has ended?


In my app I want to detect when the user lift off his second finger and is holding only one on the screen.

The problem is that my touchesEnded:withEvent: shows [[event allTouches] count] to be 2.

How can I detect which one of the touches remains on the screen?

Thanks.


Solution

  • When touch is made by user touchesBegan method triggers. You can keep the pointer to the first touch appeared. It will not be changed until the touch ends.

    EDIT:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if ([touches count] == 1)
        {
            if (!myTouch) myTouch = [touches anyObject]; //I assume myTouch is set to nil in touchesEnded
        }
        else
        {
            //perform your logic for this case
        }
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if ( myTouch && [touches containsObject: myTouch]
        {
            //perform your logic
            myTouch = nil;
        }
    }
    

    I assume you have a variable UITouch *myTouch in your class that handles touch events.