cannyboy
cannyboy

Reputation: 24426

Recognise all touches in interface

I want to be able to recognise ALL touches in an interface, no matter what was touched.

I've tried:

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

.. but this just recognises when the user taps on something that doesn't respond to taps (uiimages for instance)

The reason i need this ability is that I want to kick in a slide show if the user doesn't touch the screen for 5 minutes, so I want to reset the timer whenever they touch. It seems wrong to put this reset code in each UI event individually.

Upvotes: 1

Views: 794

Answers (5)

SVGreg
SVGreg

Reputation: 2368

There are several possible solutions, but as said @omz - overriding the sendEvent: it is the best one.

@interface YourWindow : UIWindow {
    NSDate timeOfLastTouch;
}
@end

@implementation YourWindow
 - (void)sendEvent:(UIEvent *)event {
    [super sendEvent:event];

    NSSet *touches = [event allTouches];
      UITouch *touch = [touches anyObject];
    if( touch.phase == UITouchPhaseEnded ){
         timeOfLastTouch = [NSDate date];
    }
} 



@end

Do not forget replace UIWindow with YourWindow.

Upvotes: 3

Mick F
Mick F

Reputation: 7439

As @Alladinian said in one of the comments, iOS Reference Documentation mentions that subclassing UIApplication is the right application and thus, seems preferred to subclassing UIWindow. cf. https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html :

You might decide to subclass UIApplication to override sendEvent: or sendAction:to:from:forEvent: to implement custom event and action dispatching.

Upvotes: 1

Alladinian
Alladinian

Reputation: 35686

You can subclass the UIWindow and override the sendEvent: method like this:

- (void)sendEvent:(UIEvent *)event {
  if (event.type == UIEventTypeTouches) {
     // You got a touch, do whatever you like
  };

  [super sendEvent:event];  // Let the window do the propagation of the event
}

Upvotes: 1

AppyMike
AppyMike

Reputation: 2064

you could use a tap gesture

In your interface add the UIGestureRecognizerDelegate

@interface ViewController : UIViewController <UIGestureRecognizerDelegate> {

then in your viewDidLoad add this

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod)];
tapped.delegate=self;
tapped.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapped];

then do your timer code in the tapped method

-(void)tapped {
 //timer code
}

Make sure you UI elements have setUserInteractionEnabled:YES

Upvotes: 1

omz
omz

Reputation: 53561

You could subclass UIWindow and override the sendEvent: method.

Upvotes: 3

Related Questions