如何在iOS中实现大力摇一摇?
Posted
技术标签:
【中文标题】如何在iOS中实现大力摇一摇?【英文标题】:How to achieve vigorous Shake in iOS? 【发布时间】:2012-09-03 10:25:12 【问题描述】:我在 ios 中使用摇晃功能。它与下面的代码工作正常。但是当我进行剧烈摇晃时,它检测到摇晃并在一秒钟内调用这条线if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2))
histeresisExcited = NO;
,尽管我一直在摇晃。
如何实现剧烈摇晃?
我在这里做错了什么?
// Ensures the shake is strong enough on at least two axes before declaring it a shake.
// "Strong enough" means "greater than a client-supplied threshold" in G's.
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold)
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
@interface L0AppDelegate : NSObject <UIApplicationDelegate>
BOOL histeresisExcited;
UIAcceleration* lastAcceleration;
@property(retain) UIAcceleration* lastAcceleration;
@end
实施
@implementation L0AppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
[UIAccelerometer sharedAccelerometer].delegate = self;
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
if (self.lastAcceleration)
if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7))
histeresisExcited = YES;
/* SHAKE DETECTED. DOING SOME DATABASE OPERATIONS HERE. */
else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2))
histeresisExcited = NO;
/* SHAKE STOPPED. CALLING A VIEW CONTROLLER TO DISPLAY THE CONTENTS GOT FROM THE DATABASE*/
self.lastAcceleration = acceleration;
// and proper @synthesize and -dealloc boilerplate code
@end
感谢您的帮助。
【问题讨论】:
【参考方案1】:通过对我的代码稍作改动,终于得到了答案
更改以下代码
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold)
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
到
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold)
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold) ||
(deltaY > threshold) ||
(deltaZ > threshold);
像魅力一样工作。
希望对像我这样的人有所帮助。
【讨论】:
以上是关于如何在iOS中实现大力摇一摇?的主要内容,如果未能解决你的问题,请参考以下文章