iOS事件:触摸事件.运动事件.远程控制事件

iOS中,提供了事件处理:触摸事件,运动事件,远程控制事件.这很大得方便程序猿的工作.

这里先简单做个介绍:

 1 //
 2 //  ViewController.m
 3 //  demo
 4 //
 5 //  Created by shaoting on 15/11/23.
 6 //  Copyright © 2015年 9elephas. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 
11 @interface ViewController ()
12 
13 @end
14 
15 @implementation ViewController
16 /**
17  *  IOS事件分类:1,触摸事件2,运动事件3,远程控制事件
18  1.触摸事件:触碰屏幕
19  2.运动事件:通过加速器触发(如晃动手机)
20  3.远程控制事件:通过其他设备远程控制(如蓝牙)
21  在iOS中,只有继承自UIResponder类的对象才能触发事件
22  */
23 - (void)viewDidLoad {
24     [super viewDidLoad];
25     self.title = @"iOS事件";
26     self.view.backgroundColor = [UIColor whiteColor];
27     //开个图
28     UIImage * image = [UIImage imageNamed:@"屏幕快照 2015-11-23 17.37.19"];
29     self.imageView = [[UIImageView  alloc]initWithFrame:CGRectMake(20, 20, 150, 300)];
30     self.imageView.image = image;
31     [self.view setBackgroundColor:[UIColor colorWithPatternImage:image]]; //view的背景色使用image
32     [self.view addSubview:_imageView];
33 }
34 //触摸事件
35 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
36     NSLog(@"一根手指或多根手指触摸时触发");
37     UITouch * touch = [touches anyObject]; //获得任意触摸对象
38     NSLog(@"触摸对象%@",touch);
39     CGPoint current = [touch locationInView:self.view];//获得当前的触摸对象
40     NSLog(@"当前的触摸对象%@",NSStringFromCGPoint(current));  //把CGPoint对象转换为字符串对象
41 }
42 -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
43     NSLog(@"一根或者多根手指离开屏幕时触发");
44 }
45 //以图片随鼠标移动为例
46 -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
47     NSLog(@"一根或者多根手指移动时触发");
48     UITouch * touch = [touches anyObject];
49     CGPoint current = [touch locationInView:self.view];//当前位置
50     CGPoint previous = [touch previousLocationInView:self.view];//当前位置的前一个位置
51     CGPoint center = _imageView.center;//移动前的中心位置
52     CGPoint offset = CGPointMake(current.x - previous.x, current.y - previous.y);
53     _imageView.center = CGPointMake(center.x+offset.x, center.y+offset.y);
54     NSUInteger count = touch.tapCount;//短时间内点击的次数
55     NSLog(@"短时间内点击的次数%ld",count);
56     UITouchPhase phase = touch.phase;//触摸周期内的各个状态
57     NSLog(@"触摸周期内的各个状态%ld",phase);
58     NSTimeInterval  tamp = touch.timestamp;//触摸产生或者变化的时间戳
59     NSLog(@"触摸产生或者变化的时间戳%f",tamp);
60     UIView * view = touch.view; //触摸时所在的视图
61     NSLog(@"触摸时所在的视图%@",view);
62     UIWindow * window = touch.window;//触摸时所在的window
63     NSLog(@"触摸时所在的window%@",window);
64 }
65 //运动事件
66 -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
67     NSLog(@"运动开始时触发");
68 }
69 -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
70     NSLog(@"运动结束时触发");
71 }
72 -(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
73     NSLog(@"运动被意外取消时触发");
74 }
75 //远程控制事件
76 -(void)remoteControlReceivedWithEvent:(UIEvent *)event{
77     NSLog(@"接收到远程控制消息时执行");
78 }
79 
80 - (void)didReceiveMemoryWarning {
81     [super didReceiveMemoryWarning];
82     // Dispose of any resources that can be recreated.
83 }
84 
85 @end

iOS事件:触摸事件.运动事件.远程控制事件_第1张图片

其中,模拟器开启晃动手机的功能键是:

iOS事件:触摸事件.运动事件.远程控制事件_第2张图片

触摸事件:

  1 //
  2 //  ViewController.m
  3 //  demo1
  4 //
  5 //  Created by shaoting on 15/11/23.
  6 //  Copyright © 2015年 9elephas. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #define Hight [UIScreen mainScreen].bounds.size.height-49
 11 #define Width [UIScreen mainScreen].bounds.size.width
 12 
 13 @interface ViewController ()<UIGestureRecognizerDelegate>{
 14     int _count;
 15 }
 16 @end
 17 
 18 @implementation ViewController
 19 /**
 20  *  复杂手势:6种
 21  点按手势:UITapGestureRecognizer
 22  捏合手势:UIPinchGestureRecognizer
 23  拖动手势:UIPanGetureRecognizer
 24  清扫手势:UISwipeGetureRecognizer
 25  旋转手势:UIRotationGetureReconizer
 26  长按手势:UILongPressGetureReconizer
 27  6种手势中点按手势属于离散型手势(不用判断状态),其余手势属于连续手势(除清扫手势外均需要判断状态).
 28  
 29  各手势的触发时机:点按事件:点击屏幕然后松开时触发
 30                   长按事件:长时间点击屏幕不松开即会触发(不加长按&拖动冲突解决),长时间点击屏幕松开即会触发(加长按&拖动手势冲突解决ß)
 31                   拖动事件:手指在屏幕上拖动时触发
 32                   旋转手势:手指在屏幕上旋转时触发
 33                   清扫手势:只在清扫完毕(手指清扫屏幕离开屏幕时)才会触发
 34                   捏合手势:手指捏合时触发
 35  
 36  事件冲突:点击手势会和旋转手势会发生冲突.
 37           清扫手势会和拖动手势会发生冲突.
 38  
 39  
 40  */
 41 - (void)viewDidLoad {
 42     [super viewDidLoad];
 43     [self initLayout];
 44     [self addGesture];
 45     
 46     
 47     // Do any additional setup after loading the view, typically from a nib.
 48 }
 49 //布局
 50 -(void)initLayout{
 51     _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 49, Width, Hight)];
 52     _imageView.userInteractionEnabled = YES;   //必须设置为YES,否则无法就收手势操作
 53     UIImage * image = [UIImage imageNamed:@"0"];
 54     _imageView.image = image;
 55     self.title = @"0";
 56     [self.view addSubview:_imageView];
 57 }
 58 //添加手势
 59 -(void)addGesture{
 60     UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
 61     tap.numberOfTapsRequired = 1; //设置点击次数,默认为1
 62     tap.numberOfTouchesRequired = 1;//设置为手指数
 63     [self.view addGestureRecognizer:tap];//添加手势进视图控制器上的视图
 64     
 65     UIPinchGestureRecognizer * pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
 66     [self.view addGestureRecognizer:pinch];
 67     
 68     UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
 69     [self.view addGestureRecognizer:pan];
 70     
 71     UISwipeGestureRecognizer * left = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)];
 72     left.direction = UISwipeGestureRecognizerDirectionLeft;
 73     [self.view addGestureRecognizer:left];
 74     UISwipeGestureRecognizer * right = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)];
 75     right.direction = UISwipeGestureRecognizerDirectionRight;
 76     [self.view addGestureRecognizer:right];
 77     
 78     UIRotationGestureRecognizer * rotation = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)];
 79     [self.view addGestureRecognizer:rotation];
 80     
 81     UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
 82     [self.view addGestureRecognizer:longPress];
 83 
 84     
 85     //手势冲突解决
 86     [pan requireGestureRecognizerToFail:left];
 87     [pan requireGestureRecognizerToFail:right];//解决拖动手势和清扫手势的冲突
 88     [longPress requireGestureRecognizerToFail:pan];//解决长按手势和拖动手势的冲突
 89     
 90     
 91     //多种手势在不同视图上的同时执行
 92     //iOS默认只会触发一次,因为触发是沿着响应者链依次匹配,只要匹配到响应就会停止.可以修改- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer的返回值,默认返回NO
 93     //上面演示了添加长按手势进视图控制器视图上,下面再添加长按手势到_imageView上,让这两个手势可以同时在不同视图上执行.
 94     UILongPressGestureRecognizer * longpress1 = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress1:)];
 95     longpress1.delegate = self;
 96     [_imageView addGestureRecognizer:longpress1];
 97     
 98 }
 99 //点按事件
100 //点按是否显示状态栏
101 -(void)tap:(UITapGestureRecognizer *)tap{
102     BOOL recognizer = !self.navigationController.navigationBarHidden;
103     [self.navigationController setNavigationBarHidden:recognizer];
104 }
105 //捏合事件
106 //缩放图片
107 -(void)pinch:(UIPinchGestureRecognizer *)pinch{
108 //    NSLog(@"%ld",(long)pinch.state); //  捏合状态
109     //状态:0--未开始   1--手势开始   2--手势进行  3--手势完成
110 //    typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
111 //        UIGestureRecognizerStatePossible,   // 尚未识别是何种手势操作(但可能已经触发了触摸事件),默认状态
112 //        
113 //        UIGestureRecognizerStateBegan,      // 手势已经开始,此时已经被识别,但是这个过程中可能发生变化,手势操作尚未完成
114 //        UIGestureRecognizerStateChanged,    // 手势状态发生转变
115 //        UIGestureRecognizerStateEnded,      // 手势识别操作完成(此时已经松开手指)
116 //        UIGestureRecognizerStateCancelled,  // 手势被取消,恢复到默认状态
117 //        
118 //        UIGestureRecognizerStateFailed,     // 手势识别失败,恢复到默认状态
119 //        
120 //        UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded // 手势识别完成,同UIGestureRecognizerStateEnded
121 //    };
122     if (pinch.state == UIGestureRecognizerStateChanged) {
123         _imageView.transform = CGAffineTransformMakeScale(pinch.scale, pinch.scale); //.scele记录缩放属性
124     }else if(pinch.state == UIGestureRecognizerStateEnded){ //缩放完毕后恢复
125         [UIView animateWithDuration:5 animations:^{
126             _imageView.transform = CGAffineTransformIdentity;//取消形变
127         }];
128     }
129 }
130 //拖动手势
131 -(void)pan:(UIPanGestureRecognizer *)pan{
132    
133     if (pan.state == UIGestureRecognizerStateChanged) {
134         CGPoint transform = [pan translationInView:self.view];//利用translationInView:取得在相对视图中的移动
135         _imageView.transform = CGAffineTransformMakeTranslation(transform.x, transform.y);
136     }else if(pan.state == UIGestureRecognizerStateEnded){
137         [UIView animateWithDuration:2 animations:^{
138             _imageView.transform = CGAffineTransformIdentity;
139         }];
140     }
141 }
142 
143 //清扫手势
144 -(void)swipe:(UISwipeGestureRecognizer *)swipe{
145   //因为清扫手势虽然是连续手势,但是只有在清扫完毕时才会触发,所以不用判断状态
146     if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
147         [self nextImage];
148     }
149     if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
150         [self lastImage];
151     }
152 }
153 -(void)nextImage{
154     int index=(_count+2+1)%2;
155     NSString *imageName=[NSString stringWithFormat:@"%i",index];
156     _imageView.image=[UIImage imageNamed:imageName];
157     _count=index;
158     [self showName];
159 }
160 -(void)lastImage{
161     int index=(_count+2-1)%2;
162     NSString *imageName=[NSString stringWithFormat:@"%i",index];
163     _imageView.image=[UIImage imageNamed:imageName];
164     _count=index;
165     [self showName];
166 
167 }
168 -(void)showName{
169     NSString * name = [NSString stringWithFormat:@"%i",_count];
170     self.title  = name;
171 }
172 //旋转事件
173 //旋转使图片旋转
174 -(void)rotation:(UIRotationGestureRecognizer *)rotation{
175     if (rotation.state == UIGestureRecognizerStateChanged) {
176         _imageView.transform = CGAffineTransformMakeRotation(rotation.rotation);// .rotation记录了改变的弧度
177     }else if(rotation.state == UIGestureRecognizerStateEnded){
178         [UIView animateWithDuration:2 animations:^{
179             _imageView.transform = CGAffineTransformIdentity;
180         }];
181     }
182 }
183 //长按事件
184 -(void)longPress:(UILongPressGestureRecognizer *)longPress{
185     //长按选择是否下载图片
186     if (longPress.state == UIGestureRecognizerStateBegan) {
187         UIAlertController * alterC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否下载该图片" preferredStyle:UIAlertControllerStyleActionSheet];
188         UIAlertAction * cance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
189         UIAlertAction * down = [UIAlertAction actionWithTitle:@"下载" style:UIAlertActionStyleDefault handler:nil];
190         [alterC addAction:cance];
191         [alterC addAction:down];
192         [self presentViewController:alterC animated:YES completion:nil];
193         
194     }
195 }
196 -(void)longPress1:(UILongPressGestureRecognizer *)longpress{
197     NSLog(@"添加手势进_imageView");
198 }
199 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
200     if ([otherGestureRecognizer.view isKindOfClass:[self.view class]]) {//如果是控制器视图则继续沿着响应者链传播
201         return YES;
202     }
203     return NO;
204 }
205 
206 - (void)didReceiveMemoryWarning {
207     [super didReceiveMemoryWarning];
208     // Dispose of any resources that can be recreated.
209 }
210 
211 @end

运动事件:

监听运动事件对于UI控件有个前提就是监听对象必须是第一响应者(对于UIViewController视图控制器和UIAPPlication没有此要求)。这也就意味着如果监听的是一个UI控件那么-(BOOL)canBecomeFirstResponder;方法必须返回YES。同时控件显示时(在-(void)viewWillAppear:(BOOL)animated;事件中)调用视图控制器的becomeFirstResponder方法。当视图不再显示时(在-(void)viewDidDisappear:(BOOL)animated;事件中)注销第一响应者身份。(是真的吗?)

 1 //
 2 //  ViewController.m
 3 //  demo2
 4 //
 5 //  Created by shaoting on 15/11/25.
 6 //  Copyright © 2015年 9elephas. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 
11 @interface ViewController (){
12     UIImageView * _imageView;
13 }
14 
15 @end
16 
17 @implementation ViewController
18 
19 - (void)viewDidLoad {
20     [super viewDidLoad];
21      _imageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
22     _imageView.image = [UIImage imageNamed:@"1"];
23     [self.view addSubview:_imageView];
24 }
25 
26 #pragma mark 运动开始
27 -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
28     NSLog(@"运动开始了");
29     //这里只处理摇晃事件
30     if (motion==UIEventSubtypeMotionShake) {
31         _imageView.image=[self getImage];
32     }
33 }
34 #pragma mark 运动结束
35 -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
36     NSLog(@"运动结束了");
37 }
38 -(UIImage *)getImage{
39     int index= arc4random()%2;
40     NSString *imageName=[NSString stringWithFormat:@"%i",index];
41     UIImage *image=[UIImage imageNamed:imageName];
42     return image;
43 }
44 
45 - (void)didReceiveMemoryWarning {
46     [super didReceiveMemoryWarning];
47     // Dispose of any resources that can be recreated.
48 }
49 
50 @end

远程控制事件:

这里有点问题,以后再写吧.

你可能感兴趣的:(iOS事件:触摸事件.运动事件.远程控制事件)