运动事件(MotionEvent)

在iOS中和运动相关的有三个事件:开始运动、结束运动、取消运动。

监听运动事件对于UI控件有个前提就是监听对象必须是第一响应者(对于UIViewController视图控制器和UIAPPlication没有此要求)。

这也就意味着如果监听的是一个UI控件那么

-(BOOL)canBecomeFirstResponder;方法必须返回YES。

同时控件显示时(在-(void)viewWillAppear:(BOOL)animated;事件中)调用视图控制器的becomeFirstResponder方法。

当视图不再显示时(在-(void)viewDidDisappear:(BOOL)animated;事件中)注销第一响应者身份。

第一响应者会收到所有的触摸事件及动作事件。与动作有关的回调,分别对应于UIView里面的各种触摸回调。

这些回调方法是: motionBegan:withEvent: 这个回调方法会在动作事件刚开始的时候执行。

目前系统只能识别一种动作事件,即晃动(shake)。

以后也许还能识别其他类型的动作,所以我们应该用代码来判断动作类型。

motionEnded:withEvent: 动作事件结束时,第一响应者会收到这个回调。

motionCancelled:withEvent: 与触摸事件一样,动作事件也会由于打进来的电话或其他系统事件而取消。

苹果公司建议开发者在编写实际代码时,应该把与动作事件有关的三个回调方法全都实现好。

 1 -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
 2 {
 3     if (motion==UIEventSubtypeMotionShake) 
 4 
 5         NSLog(@"晃动开始");
 6 }
 7 -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
 8 {
 9     if (motion==UIEventSubtypeMotionShake) {
10         NSLog(@"晃动结束");
11     }
12 }
13 -(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
14 {
15     if (motion==UIEventSubtypeMotionShake) 
16 
17     NSLog(@"被打断");
18 }
原文地址:https://www.cnblogs.com/kfgcs/p/6387161.html