1. 程式人生 > >IOS檢測晃動的兩種方式

IOS檢測晃動的兩種方式

第一種:

第一步:在AppDelegate中設定如下:

- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   application.applicationSupportsShakeToEdit = YES;
}

第二步:在相應的viewController中新增相應的程式碼如下:

-(BOOL)canBecomeFirstResponder {
    returnYES;
}

-(void)viewDidAppear:(BOOL)animated {
    [superviewDidAppear:animated];
    [selfbecomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [selfresignFirstResponder];
    [superviewWillDisappear:animated];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
    if (motion== UIEventSubtypeMotionShake) {
       NSLog(@"檢測到晃動");
    }
}

在模擬器中測試晃動,按組合鍵:Ctrl + Win + Z

第二種:

利用UIAccelerometer加速器來檢測,程式碼如下:

- (void)viewDidLoad
{

   UIAccelerometer *accelerometer = [UIAccelerometersharedAccelerometer];
   accelerometer.delegate = self;
   accelerometer.undateInterval = 1.0f / 60.0f;

}
- (void)accelerometer:(UIAccelerometer *)accelerometerdidAccelerate:(UIAcceletration *)acceleration
{
if(fabsf(acceleration.x)>2.0||fabsf(acceleration.y>2.0)||fabsf(acceleration.z)>2.0)
    {
       //NSLog(@"檢測到晃動");
    }
}