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

孤街醉人 提交于 2019-12-05 07:21:47

问题


I want to a "Shake Device" event to my app - i.e., 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?


回答1:


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;
}



回答2:


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

[self becomeFirstResponder];

Give that a try.




回答3:


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;
}


来源:https://stackoverflow.com/questions/6806937/ios-how-to-implement-a-shake-device-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!