第一种

1、在AppDelegate.h中进行如下设置:

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. application.applicationSupportsShakeToEdit = YES;
  4. }

2、在你需要对晃动事件进行处理的ViewController中添加如下代码:

  1. -(BOOL)canBecomeFirstResponder {
  2. return YES;
  3. }
  4. -(void)viewDidAppear:(BOOL)animated {
  5. [super viewDidAppear:animated];
  6. [self becomeFirstResponder];
  7. }
  8. - (void)viewWillDisappear:(BOOL)animated {
  9. [self resignFirstResponder];
  10. [super viewWillDisappear:animated];
  11. }
  12. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  13. {
  14. if (motion == UIEventSubtypeMotionShake) {
  15. NSLog(@"检测到晃动");
  16. }
05-02 07:26