1

I have a custom class (MyEventHandler) which has nothing to do with the UI in my app. I would like it to be able to catch a MotionShake event. As I understand I need to make MyEventHandler a first responder for that.

Here's what I've done. I inherited MyEventHandler from UIResponder and implemented canBecomeFirstResponder method. However when I call becomeFirstResponder it returns 0, so does the [self isFirstResponder].

I checked the current first responder and it turned out to be nil.

If I do the same things with my ViewController it works fine, so my question is: is it even possible to make a custom class, which doesn't inherit from UIView, a first responder?

Here's the code that I have:

@interface MyEventHandler : UIResponder
  - (void)start;
@end

@implementation MyEventHandler
- (void)start {
      [self becomeFirstResponder];
  }

- (BOOL)canBecomeFirstResponder {
      return YES;
  }
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
      if (motion == UIEventSubtypeMotionShake) {
          NSLog(@"Shake-shake-shake!");
      }
  }

@end
oranJess
  • 588
  • 1
  • 5
  • 17

1 Answers1

0

If you call becomeFirstResponder on a View object that is not on view hierarchy, it will return nil.

For your purpose, you can make use of notifications to tell your custom class(MyEventHandler) when you recieve the motion event on your ViewController

Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
  • 1
    I'm trying to build a Framework that can be embedded in any application, so I can't modify the app's ViewControllers. As for the `becomeFirstResponder` I call it in `MyEventHandler` class, not in a View. And `MyEventHandler` only inherits from `UIResponder`. – oranJess Apr 15 '14 at 10:26
  • @oranJess I'm doing this exact thing now, did you figure it out? – Michael Ozeryansky Jun 12 '18 at 20:32