iPhone Shake event not properly working

2019-07-16 18:38发布

问题:

I have this inside my viewController:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    if (event.type == UIEventSubtypeMotionShake) {

        NSLog(@"I have shaked");

    }
}

Why is this not working? Edit:


I do infact have this:

- (void) viewWillAppear:(BOOL)animated
{
    [shakeView becomeFirstResponder];
    [super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [shakeView resignFirstResponder];
    [super viewWillDisappear:animated];
}

回答1:

If the UIViewController is loaded at the very start of the application, I've seen an odd glitch in OS 3.0 where it would not become the first responder unless you delayed the appropriate message a bit. Try placing

[self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.3];

within -loadView or something else that is called when the controller is first set up.

There may be a more elegant way to work around this, but this approach has worked for me.



回答2:

The viewController must be the first responder during the shake to receive this event.

This could be one reason it's not working.