IOS 3.0 + 开始支持motion事件,检测设备摇动
– motionBegan:withEvent: 摇动开始时执行
– motionEnded:withEvent: 摇动结束时执行
– motionCancelled:withEvent: 摇动被取消时执行
具体检测代码如下:
1、 在AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *) launchOptions{
...
application.applicationSupportsShakeToEdit = YES;//添加此处
...
return YES;
}
2、在viewController中加入
-(BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if (motion == UIEventSubtypeMotionShake)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"摇一摇!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
}