文章目录
  1. 1. IOS中实现设备摇动检测
  2. 2. IOS中实现设备摇动检测

IOS中实现设备摇动检测

Ios基础语法 Ios手势 Ios设备动作

IOS中实现设备摇动检测

这些方法都是在网上看到的,我自己经过测试的就这2种;

1.UIWindow(已测试)

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

{

}

  • (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

    if (motion == UIEventSubtypeMotionShake )

    {

        //这里可以促发系统震动,或者发送一个通知,进行相应的处理

    }

}

  • (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

{    

}

2. UIViewController(继承自UIResponder - 已测试)

-(BOOL)canBecomeFirstResponder {

    returnself.shakeSyncIsOn;//这里是self拥有的一个变量,通过这个变量来设置为第一个激活的responder,只有这个方法返回为true时才可以摇动

}

-(void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];

    if ([selfcanBecomeFirstResponder]==YES)

    {

        NSLog(@”becomeFirstResponder:YES”);

   //下面这句代码,不一定非得写到viewDidLoad或者applicationDidFinishLaunch中,这里也可以

        [[UIApplicationsharedApplication] setApplicationSupportsShakeToEdit:YES];

        [selfbecomeFirstResponder];

    }

    else{

        NSLog(@”becomeFirstResponder:NO”);

    }

}

  • (void)viewWillDisappear:(BOOL)animated {

    [selfresignFirstResponder];

    [super viewWillDisappear:animated];

}

 

#pragma mark - 

#pragma mark - shakeToSync: UIResponder support motion

//开始摇动检测

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

{

    NSLog(@”====== Shake Begins =======”);

}

-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

    NSLog(@”======= Shake Canceled =======”);

}

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

{

       if (motion == UIEventSubtypeMotionShake)

      {

           NSLog(@”======== Shake End ========”);

    //这里可以添加震动反馈,或者发送一个通知

    //AudioToolBox.framework

     //_#import “AudioToolbox/AudioToolbox.h”�_�
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

      }

}

文章目录
  1. 1. IOS中实现设备摇动检测
  2. 2. IOS中实现设备摇动检测