简体   繁体   中英

iOS: How to Implement a “Shake Device” event?

I want to a "Shake Device" event to my app - ie, when the user shakes the device something happens. I tried implementing:

-(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake) {
        //something happens
    }
}

It doesn't seem to work.......
Does anyone knows which method I should use?

Try using the below code, it worked fine for me.

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if ( event.subtype == UIEventSubtypeMotionShake )
       {
          //your code
       }

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
                [super motionEnded:motion withEvent:event];
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

Might be to late to answer but in your viewDidLoad you need to include.

[self becomeFirstResponder];

Give that a try.

In addition to Taylor's solution, also make sure that your AppDelegate.m has this in it.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    application.applicationSupportsShakeToEdit = YES;
    return YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM