试图检测震动,从未调用motionEnded

Luk*_*uke 1 objective-c motion-detection shake ios

我试图在iOS6中发现一个摇晃,似乎每个例子都是在2009年左右写回来的iOS3,没有任何工作应该如此.这是我的方法:

- (void) motionEnded: (UIEventSubtype) motion withEvent: (UIEvent *) event {
    if (motion == UIEventSubtypeMotionShake) NSLog(@"Detected a shake");
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了Apple的建议(制作一个canBecomeFirstResponder返回YES并调用它的方法),但它没有做任何事情.它被称为罚款,但对震动没有被识别没有影响.

我已经阅读了一些关于需要创建我的视图的自定义版本的东西,但我真的不想搞砸,因为我没有以编程方式创建视图,而且有四个左右.

提前致谢!

小智 15

在viewController中你必须覆盖方法caneBecomeFirstResponder并回答是,在viewDidAppear中你必须将viewController(self)设置为第一个响应者.这是代码:

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) NSLog(@"Detected a shake");
}

-(BOOL)canBecomeFirstResponder {
    return YES;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)