1.在App's Delegate中设定applicationSupportsShakeToEdit属性
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
application.applicationSupportsShakeToEdit= YES; //在ios6.0后,这里其实都可以不写了
self.window= [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];
// Override point for customization after application launch.
self.viewController= [[ViewControlleralloc] initWithNibName:@"ViewController"bundle:nil];
self.window.rootViewController= self.viewController;
[self.windowmakeKeyAndVisible];
returnYES;
}
2.在你的View控制器中添加/重载canBecomeFirstResponder, viewDidAppear:以及viewWillDisappear:
//这里很重要,因为大部分视图 默认 的 canBecomeFirstResponder 是 NO的
-(BOOL)canBecomeFirstResponder {
**return **YES;
}
-(**void**)viewDidAppear:(BOOL)animated {
[**super **viewDidAppear:animated];
[**self **becomeFirstResponder];
}
-(**void**)viewWillDisappear:(BOOL)animated {
[**self **resignFirstResponder];
[**super **viewWillDisappear:animated];
}
3.在你的view控制器中添加motionEnded:
-(**void**)motionEnded:(**UIEventSubtype**)motion withEvent:(**UIEvent***)**event**
{
**if**(motion == **UIEventSubtypeMotionShake**)
{
*// your code*
}
}
IOS 3.0 + 开始支持motion事件,检测设备摇动
– motionBegan:withEvent: 摇动开始时执行
– motionEnded:withEvent: 摇动结束时执行
– motionCancelled:withEvent: 摇动被取消时执行
经过试验
UIViewController
UIWindow
UIView 都可以支持摇一摇
根本是在 motion的一系列回调 以及 canBecomeFirstResponder 等方法 都是 UIResponder 类的特性