다음 코드가 도움이 될 수 있습니다. 나는 그것을 잠시 뒤로 찾았고 (기억하지 않고) 그것을 청소했다. 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 의정서를 이행 할 필요가있다. 쉐이크가 감지 될 때마다 onShake 메시지가 대리자 객체로 전송됩니다.