有两种方式检测摇动:
1. 继承UIWindow
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { } - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake ) { // User was shaking the device. Post a notification named "shake". [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self];//消息注册 } } - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { }
2. 在AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... application.applicationSupportsShakeToEdit = YES;//添加此处 ... return YES; }
然后在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) { NSLog(@"摇啊摇"); } }
原文:
http://ilewen.com/questions/778/%E7%A8%8B%E5%BA%8F%E6%80%8E%E4%B9%88%E6%A3%80%E6%B5%8B%E7%94%A8%E6%88%B7%E5%9C%A8%E6%91%87%E5%8A%A8iphone%EF%BC%9F