IOS檢測晃動的兩種方式

chenyxh2005發表於2014-12-09

第一種:

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

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

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

-(BOOL)canBecomeFirstResponder {
    return YES;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

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

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

第二種:

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

- (void)viewDidLoad
{

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

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

相關文章