震动检测主要分为下面4个步骤,依次实现即可
// step1
@interface UIWindow (MotionRecognizing)
@end
@interface UIResponder (MotionRecognizers)
/** Registers the receiver for future motion events.
The `action` message will be sent to the receiver when a motion event occurs and is
not intercepted in the responder chain. The `action` selector must take exactly one
parameter of type NSNotification.
You must not add a motion recognizer more than once.
*/
- (void) addMotionRecognizerWithAction:(SEL)action;
/** You must call this before deallocating the receiver. */
- (void) removeMotionRecognizer;
@end
@implementation UIWindow (MotionRecognizing)
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake)
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"CPDeviceShaken" object:self];
}
}
@end
@implementation UIResponder (MotionRecognizers)
- (void) addMotionRecognizerWithAction:(SEL)action
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:action name:@"CPDeviceShaken" object:nil];
}
- (void) removeMotionRecognizer
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"CPDeviceShaken" object:nil];
}
@end
// step2:
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Step 2 - Register for motion event:
[self addMotionRecognizerWithAction:@selector(motionWasRecognized:)];
}
// step3:
- (void) viewDidDisappear:(BOOL)animated
{
// Step 3 - Unregister:
[self removeMotionRecognizer];
[super viewDidDisappear:animated];
}
// step4
- (void) motionWasRecognized:(NSNotification*)notif
{
// 震动后,在这里实现结果
}
另外有实现屏幕震动的代码: