iOS开发 - 检测晃动/摇一摇功能UIAccelerometer与motion实现

iOS检测晃动/摇一摇功能实现

app开发中,要实现检测晃动/摇一摇功能,下面记录下两种方案

方案一 利用UIAccelerometer加速器来检测


- (void)viewDidLoad
{

   UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
   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(@"检测到晃动");
    }
}

方案二 motion


// 第一步:在AppDelegate中设置如下:

- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(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(@"检测到晃动");
    }
}

你可能感兴趣的:(iphone开发,移动开发,Objective-c,ios,cocoa,macos)