简体   繁体   中英

How to detect light motion shake in iPhone?

I am creating an app and currently It has a reaction to a motion shake and this is the code for the shake:

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

Now the user must really shake hardly for the reaction to happen, is there any more complicated way to detect a light wave, or like 5 light shake's and then the reaction?

Try the following

in your file's .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

in your file's .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;
}

I used a subclass of UIView, you could use whatever you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM