标签:
摇一摇功能的实现
在AppStore中多样化功能越来越多的被使用了,所以今天就开始介绍一些iOS开发的比较实用,但是我们接触的比较少的功能,我们先从摇一摇功能开始
在 UIResponder中存在这么一套方法
1 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); 2 3 - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); 4 - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
这就是执行摇一摇的方法。那么怎么用这些方法呢?
很简单,你只需要让这个Controller本身支持摇动
同时让他成为第一相应者:
1 - (void)viewDidLoad 2 3 4 { 5 6 7 [superviewDidLoad]; 8 9 10 // Do any additional setup after loading the view, typically from a 11 nib. 12 13 14 [[UIApplicationsharedApplication] 15 setApplicationSupportsShakeToEdit:YES]; 16 17 18 [self 19 20 21 becomeFirstResponder]; 22 23 24 }
1 - (void) motionBegan:(UIEventSubtype)motion 2 withEvent:(UIEvent 3 4 5 *)event 6 7 8 { 9 10 11 //检测到摇动 12 13 14 } 15 16 17 - (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent 18 *)event 19 20 21 { 22 23 24 //摇动取消 25 26 27 } 28 29 30 31 - (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent 32 *)event 33 34 35 36 { 37 38 39 //摇动结束 40 41 42 if 43 (event.subtype == UIEventSubtypeMotionShake) { 44 45 46 //something 47 happens 48 49 50 51 } 52 53 54 }
下面我们开始简单的使用它:
1 - (void)viewDidAppear:(BOOL)animated 2 { 3 [super viewDidAppear:animated]; 4 [self becomeFirstResponder]; 5 } 6 - (void) viewWillAppear:(BOOL)animated 7 { 8 [self resignFirstResponder]; 9 [super viewWillAppear:animated]; 10 } 11 -(BOOL)canBecomeFirstResponder 12 { 13 return YES; 14 } 15 - (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event 16 { 17 18 if (motion == UIEventSubtypeMotionShake) { 19 NSLog(@"摇一摇"); 20 } 21 }
另外值得一提的是,在模拟器中运行时,可以通过「Hardware」-「Shake Gesture」来测试「摇一摇」功能。
标签:
原文地址:http://www.cnblogs.com/iCocos/p/4598522.html