How do I detect when someone shakes an iPhone?

后端 未结 16 1889
后悔当初
后悔当初 2020-11-22 06:41

I want to react when somebody shakes the iPhone. I don\'t particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know h

16条回答
  •  悲哀的现实
    2020-11-22 06:53

    Easiest solution is to derive a new root window for your application:

    @implementation OMGWindow : UIWindow
    
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if (event.type == UIEventTypeMotion && motion == UIEventSubtypeMotionShake) {
            // via notification or something   
        }
    }
    @end
    

    Then in your application delegate:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.window = [[OMGWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        //…
    }
    

    If you are using a Storyboard, this may be trickier, I don’t know the code you will need in the application delegate precisely.

提交回复
热议问题