iOS檢測晃動/搖一搖功能實(shí)現(xiàn)文章來源:http://www.zghlxwxcb.cn/news/detail-563523.html
app開發(fā)中,要實(shí)現(xiàn)檢測晃動/搖一搖功能,下面記錄下兩種方案文章來源地址http://www.zghlxwxcb.cn/news/detail-563523.html
方案一 利用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中設(shè)置如下:
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
application.applicationSupportsShakeToEdit = YES;
}
// 第二步:在相應(yīng)的viewController中添加相應(yīng)的代碼如下:
-(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(@"檢測到晃動");
}
}
到了這里,關(guān)于iOS開發(fā) - 檢測晃動/搖一搖功能UIAccelerometer與motion實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!