2012-08-03 33 views
0

我創建一個應用程序,目前它有一個運動抖動的反應,這是搖代碼:如何檢測iPhone中的輕微震動?

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event 
    { 
     if (event.type == UIEventSubtypeMotionShake) {} 
    } 

現在,用戶必須真正撼動很難以使反應發生,有沒有更多的複雜的方式來檢測光波,或者像5光搖一樣然後反應?

回答

1

嘗試在你的文件的.H

#import <UIKit/UIKit.h> 

@interface ShakeUIView : UIView <UIAccelerometerDelegate>{ 
    BOOL hasBeenShaken; 
    UIAcceleration* lastAction; 
    id delegate; 
} 

@property(strong) UIAcceleration* lastAction; 
@property (nonatomic, assign) id delegate; 

@end 

在你的文件的.M

#import "ShakeUIView.h" 

@implementation ShakeUIView 

@synthesize lastAction; 

// adjust the threshold to increase/decrease the required amount of shake 
static BOOL SJHShaking(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)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
      } 
    return self; 
} 

-(void)awakeFromNib{ 
    [super awakeFromNib]; 
    [UIAccelerometer sharedAccelerometer].delegate = self; 
} 

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { 

    if (self.lastAction) { 
     if (!hasBeenShaken && SJHShaking(self.lastAction, acceleration, 0.7)) { 
      hasBeenShaken = YES; 
      // Shake detacted do what you want here 

     } else if (hasBeenShaken && !SJHShaking(self.lastAction, acceleration, 0.2)) { 
      hasBeenShaken = NO; 
     } 
    } 

    self.lastAction = acceleration; 
} 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 
} 
*/ 

-(void)dealloc{ 
    [UIAccelerometer sharedAccelerometer].delegate = nil; 
} 

我用的UIView的子類以下

,你可以使用任何你想要的。