也許下面的代碼可以幫助你。我發現它有一段時間(不記得在哪裏)並清理乾淨。您可以調整didAccelerate中的值(當前爲0.8和0.2),以確定它對抖動的敏感程度,以及您必須保持設備再次抖動的穩定程度。
頁眉
@protocol ShakeHelperDelegate
-(void) onShake;
@end
@interface ShakeHelper : NSObject <UIAccelerometerDelegate>
{
BOOL histeresisExcited;
UIAcceleration* lastAcceleration;
NSObject<ShakeHelperDelegate>* delegate;
}
+(id) shakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del;
-(id) initShakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del;
@end
實施
#import "ShakeHelper.h"
@interface ShakeHelper (Private)
@end
@implementation ShakeHelper
// 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 AccelerationIsShaking(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);
}
+(id) shakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del
{
return [[[self alloc] initShakeHelperWithDelegate:del] autorelease];
}
-(id) initShakeHelperWithDelegate:(NSObject<ShakeHelperDelegate>*)del
{
if ((self = [super init]))
{
delegate = del;
[UIAccelerometer sharedAccelerometer].delegate = self;
}
return self;
}
-(void) accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
if (lastAcceleration)
{
if (!histeresisExcited && AccelerationIsShaking(lastAcceleration, acceleration, 0.8))
{
histeresisExcited = YES;
[delegate onShake];
}
else if (histeresisExcited && !AccelerationIsShaking(lastAcceleration, acceleration, 0.2))
{
histeresisExcited = NO;
}
}
[lastAcceleration release];
lastAcceleration = [acceleration retain];
}
-(void) dealloc
{
CCLOG(@"dealloc %@", self);
[UIAccelerometer sharedAccelerometer].delegate = nil;
[lastAcceleration release];
[super dealloc];
}
@end
你使用這樣的:
[ShakeHelper shakeHelperWithDelegate:self];
顯然,自對象需要實現ShakeHelperDelegate協議。每當檢測到抖動時,Shake消息都將發送到委託對象。