振动检测

震动检测主要分为下面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 
{
      // 震动后,在这里实现结果
}

另外有实现屏幕震动的代码:

stackoverflow shake visual screen use coreanimation

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值