原文地址:http://hi.baidu.com/dark_jm/item/fb9249fb50cf88dd6225d26d
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 类的特性
我找到的另一篇文章:http://my.csdn.net/baihongliwin8/code/detail/36010
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
微信的摇一摇是怎么实现的~发现原来 ios本身就支持
在 UIResponder中存在这么一套方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
这就是执行摇一摇的方法。那么怎么用这些方法呢?
很简单,你只需要让这个Controller本身支持摇动
同时让他成为第一相应者:
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[UIApplicationsharedApplication] setApplicationSupportsShakeToEdit:YES];
[selfbecomeFirstResponder];
}
然后去实现那几个方法就可以了
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//检测到摇动
}
- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//摇动取消
}
- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//摇动结束
if (event.subtype == UIEventSubtypeMotionShake) {
//something happens
}
}
|