Aluminum
Aluminum

Reputation: 2992

How to detect when no fingers are on the screen?

I need some help with the touchesEnded function. I want to start a NSTimer when there are no fingers on the screen using the touchesEnded function. Is this possible?. Currently I have a touchesBegan function working :-).

Here's my code:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSUInteger numTaps = [[touches anyObject] tapCount];

    if (numTaps >= 2)
    {
        self.label.text = [NSString stringWithFormat:@"%d", numTaps];
        self.label2.text = @"+1";
        [self.button setHidden:YES];
    }
}

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

- (void)showButton
{
    [self.button setHidden:NO];
}

Upvotes: 1

Views: 404

Answers (2)

jrturton
jrturton

Reputation: 119242

To create an idle timer, the simplest way is to create a custom subclass of UIApplication, and override sendEvent: - here, call super, and reset your timer. This will cover all touches for you. Every touch your app receives goes through this method.

To use the custom application subclass you need to modify the call in main.m to UIApplicationMain(), inserting your custom class name.

Upvotes: 2

matt
matt

Reputation: 535169

It's tricky. You don't get an event that tells you that all fingers are up; each touchesEnded only tells you that this finger is up. So you have to keep track of touches yourself. The usual technique is to store touches in a mutable set as they arrive. But you can't store the touches themselves, so you have to store an identifier instead.

Start by putting a category on UITouch, to derive this unique identifier:

@interface UITouch (additions)
- (NSString*) uid;
@end

@implementation UITouch (additions)
- (NSString*) uid {
    return [NSString stringWithFormat: @"%p", self];
}
@end

Now we must maintain our mutable set throughout the period while we have touches, creating it on our first touch and destroying it when our last touch is gone. I'm presuming you have an NSMutableSet instance variable / property. Here is pseudo-code:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // create mutable set if it doesn't exist
    // then add each touch's uid to the set with addObject:
    // and then go on and do whatever else you want to do
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // remove uid of *every* touch that has ended from our mutable set
    // if *all* touches are gone, nilify the set
    // now you know that all fingers are up
}

Upvotes: 3

Related Questions