iOS : How to detect Shake motion?

前端 未结 4 992
甜味超标
甜味超标 2021-01-31 10:01

I added the following code to my appDelegate.m

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

- (void)motionEnded:(UIEventSubtype)mot         


        
4条回答
  •  情话喂你
    2021-01-31 10:41

    You could do something like this...

    Firstly...

    Set the applicationSupportsShakeToEdit property in the App's Delegate:

    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
        application.applicationSupportsShakeToEdit = YES;
    
        [window addSubview:viewController.view];
        [window makeKeyAndVisible];
    }
    

    Secondly...

    Add/Override canBecomeFirstResponder, viewDidAppear: and viewWillDisappear: methods in your View Controller:

    -(BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    -(void)viewDidAppear:(BOOL)animated {
       [super viewDidAppear:animated];
       [self becomeFirstResponder];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [self resignFirstResponder];
        [super viewWillDisappear:animated];
     }
    

    Thirdly...

    Add the motionEnded method to your View Controller:

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

    That should work if the first answer did not and this is only quickly typed not tested:)

提交回复
热议问题