iOS开发摇动手势实现详解
时间:2014-07-22 23:11:54
收藏:0
阅读:758
1.当设备摇动时,系统会算出加速计的值,并告知是否发生了摇动手势。系统只会运动开始和结束时通知你,并不会在运动发生的整个过程中始终向你报告每一次运动。例如,你快速摇动设备三次,那只会收到一个摇动事件。
2,想要实现摇动手势,首先需要使视图控制器成为第一响应者,注意不是单独的控件。成为第一响应者最恰当的时机是在视图出现的时候,而在视图消失的时候释放第一响应者。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
-( BOOL )canBecomeFirstResponder { return
YES ; } -( void )viewDidAppear:( BOOL )animated { [ super
viewDidAppear:animated]; [ self
becomeFirstResponder]; } -( void )viewWillDisappear:( BOOL )animated { [ self
resignFirstResponder]; [ super
viewWillDisappear:animated]; } |
现在,视图控制器准备处理运动事件,其中有三个方法,motionBegan,motionEnded和motionCancelled,这些与触摸方法有着相似的工作原理,但没有移动方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 |
- ( void )motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { if
(event.type == UIEventSubtypeMotionShake) { NSLog (@ "Shake Began" ); } } -( void )motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if
(event.type == UIEventSubtypeMotionShake) { NSLog (@ "Shake End" ); } } -( void )motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { if
(event.type == UIEventSubtypeMotionShake) { NSLog (@ "Shake Cancelled" ); } } |
以上是转载自http://blog.csdn.net/marvindev
我的代码:
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 |
// // ocqViewController.m // shake // // Created by ocq on 14-4-29. // Copyright (c) 2014年 ocq. All rights reserved. // #import "ocqViewController.h" @interface
ocqViewController () @end @implementation
ocqViewController - ( void )viewDidLoad { [ super
viewDidLoad]; NSLog (@ "初始化了实例" ); // Do any additional setup after loading the view, typically from a nib. } - ( void )didReceiveMemoryWarning { [ super
didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -( BOOL )canBecomeFirstResponder { return
YES ; } -( void )viewDidAppear:( BOOL )animated { [ super
viewDidAppear:animated]; [ self
becomeFirstResponder]; } -( void )viewWillDisappear:( BOOL )animated { [ self
resignFirstResponder]; [ super
viewWillDisappear:animated]; } ////当手机移动结束时调用该方法 #pragma motion移动的类型 UIEvent事件 - ( void )motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { //如果是摇手机类型的事件 if (motion==UIEventSubtypeMotionShake){ |
1 |
NSLog (@ "摇动了手机" ); |
1 |
//创建并初始化对话框 UIAlertView *show=[[UIAlertView alloc] initWithTitle:@"ocq ios 学习" message:@"恭喜,您查找到了好友" delegate:nil cancelButtonTitle:@"添加为好友" otherButtonTitles: nil]; //显示对话框 [show show]; // [show release]; <br>} <br>} <br>@end<br><br> |
评论(0)