IOS 七种手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)详解及实例代码

时间:2022-09-19 16:44:12

ios 七种手势操作

今天为大家介绍一下ios 的七种手势,手势在开发中经常用到,所以就简单 通俗易懂的说下, 话不多说,直接看代码:

1、uigesturerecognizer 介绍

手势识别在 ios 中非常重要,他极大地提高了移动设备的使用便捷性。

ios 系统在 3.2 以后,他提供了一些常用的手势(uigesturerecognizer 的子类),开发者可以直接使用他们进行手势操作。

  1. uipangesturerecognizer(拖动)
  2. uipinchgesturerecognizer(捏合)
  3. uirotationgesturerecognizer(旋转)
  4. uitapgesturerecognizer(点按)
  5. uilongpressgesturerecognizer(长按)
  6. ​uiswipegesturerecognizer(轻扫)

另外,可以通过继承 uigesturerecognizer 类,实现自定义手势(手势识别器类)。

ps:自定义手势时,需要 #import <uikit/uigesturerecognizersubclass.h>,一般需实现如下方法:

?
1
2
3
4
5
6
7
- (void)reset;
 
- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event;
- (void)touchesmoved:(nsset *)touches withevent:(uievent *)event;
- (void)touchesended:(nsset *)touches withevent:(uievent *)event;
- (void)touchescancelled:(nsset *)touches withevent:(uievent *)event;
//以上方法在分类 uigesturerecognizer (uigesturerecognizerprotected) 中声明,更多方法声明请自行查看

uigesturerecognizer 的继承关系如下:

IOS 七种手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)详解及实例代码

 2、手势状态

在六种手势识别中,只有一种手势是离散型手势,他就是 uitapgesturerecognizer。

离散型手势的特点就是:一旦识别就无法取消,而且只会调用一次手势操作事件(初始化手势时指定的回调方法)。

​换句话说其他五种手势是连续型手势,而连续型手势的特点就是:会多次调用手势操作事件,而且在连续手势识别后可以取消手势。从下图可以看出两者调用操作事件的次数是不同的:

IOS 七种手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)详解及实例代码

手势状态枚举如下:

?
1
2
3
4
5
6
7
8
9
typedef ns_enum(nsinteger, uigesturerecognizerstate) {
  uigesturerecognizerstatepossible,  // 尚未识别是何种手势操作(但可能已经触发了触摸事件),默认状态
  uigesturerecognizerstatebegan,   // 手势已经开始,此时已经被识别,但是这个过程中可能发生变化,手势操作尚未完成
  uigesturerecognizerstatechanged,  // 手势状态发生转变
  uigesturerecognizerstateended,   // 手势识别操作完成(此时已经松开手指)
  uigesturerecognizerstatecancelled, // 手势被取消,恢复到默认状态
  uigesturerecognizerstatefailed,   // 手势识别失败,恢复到默认状态
  uigesturerecognizerstaterecognized = uigesturerecognizerstateended // 手势识别完成,同uigesturerecognizerstateended
};

对于离散型手势 uitapgesturerecgnizer 要么被识别,要么失败,点按(假设点按次数设置为1,并且没有添加长按手势)下去一次不松开则此时什么也不会发生,松开手指立即识别并调用操作事件,并且状态为3(已完成)。

但是连续型手势要复杂一些,就拿旋转手势来说,如果两个手指点下去不做任何操作,此时并不能识别手势(因为我们还没旋转)但是其实已经触发了触摸开始事件,此时处于状态0;如果此时旋转会被识别,也就会调用对应的操作事件,同时状态变成1(手势开始),但是状态1只有一瞬间;紧接着状态变为2(因为我们的旋转需要持续一会),并且重复调用操作事件(如果在事件中打印状态会重复打印2);松开手指,此时状态变为3,并调用1次操作事件。

3、使用手势的步骤

使用手势很简单,分为三步:

  1. 创建手势识别器对象实例。创建时,指定一个回调方法,当手势开始,改变、或结束时,执行回调方法。
  2. 设置手势识别器对象实例的相关属性(可选部分)
  3. 添加到需要识别的 view 中。每个手势只对应一个 view,当屏幕触摸在 view 的边界内时,如果手势和预定的一样,那就会执行回调方法。

ps:一个手势只能对应一个 view,但是一个 view 可以有多个手势。建议在真机上测试这些手势,模拟器操作不太方便,可能导致认为手势失效的情况。(模拟器测试捏合和旋转手势时,按住 option 键,再用触摸板或鼠标操作)

4、举例说明

功能描述:

附加到两个图片视图 uiimageview 的有『拖动』、『捏合』、『旋转』、『点按』;

而『轻扫』和『自定义手势 kmgesturerecognizer』附加在根视图 uiview 中。

拖动:进行当前图片视图位置移动

捏合:进行当前图片视图缩放

旋转:进行当前图片视图角度旋转

点按:双击恢复当前图片视图的缩放、角度旋转、不透明度

长按:设置当前图片视图的不透明度为0.7

轻扫:左右轻扫设置两个图片视图为居中,同时以垂直居中的特定偏移量定位

自定义手势:挠痒功能,左右扫动共3次或以上,设置两个图片视图为居中,同时以水平居中的特定偏移量定位

效果如下:

IOS 七种手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)详解及实例代码

kmgesturerecognizer.h

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import <uikit/uikit.h>
 
typedef ns_enum(nsuinteger, direction) {
  directionunknown,
  directionleft,
  directionright
};
 
@interface kmgesturerecognizer : uigesturerecognizer
@property (assign, nonatomic) nsuinteger ticklecount; //挠痒次数
@property (assign, nonatomic) cgpoint currentticklestart; //当前挠痒开始坐标位置
@property (assign, nonatomic) direction lastdirection; //最后一次挠痒方向
 
@end

kmgesturerecognizer.m

?
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
#import "kmgesturerecognizer.h"
#import <uikit/uigesturerecognizersubclass.h>
 
@implementation kmgesturerecognizer
#define kminticklespacing 20.0
#define kmaxticklecount 3
 
- (void)reset {
  _ticklecount = 0;
  _currentticklestart = cgpointzero;
  _lastdirection = directionunknown;
  
  if (self.state == uigesturerecognizerstatepossible) {
    self.state = uigesturerecognizerstatefailed;
  }
}
 
- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event {
  uitouch *touch = [touches anyobject];
  _currentticklestart = [touch locationinview:self.view]; //设置当前挠痒开始坐标位置
}
 
- (void)touchesmoved:(nsset *)touches withevent:(uievent *)event {
  //『当前挠痒开始坐标位置』和『移动后坐标位置』进行 x 轴值比较,得到是向左还是向右移动
  uitouch *touch = [touches anyobject];
  cgpoint tickleend = [touch locationinview:self.view];
  cgfloat ticklespacing = tickleend.x - _currentticklestart.x;
  direction currentdirection = ticklespacing < 0 ? directionleft : directionright;
  
  //移动的 x 轴间距值是否符合要求,足够大
  if (abs(ticklespacing) >= kminticklespacing) {
    //判断是否有三次不同方向的动作,如果有则手势结束,将执行回调方法
    if (_lastdirection == directionunknown ||
      (_lastdirection == directionleft && currentdirection == directionright) ||
      (_lastdirection == directionright && currentdirection == directionleft)) {
      _ticklecount++;
      _currentticklestart = tickleend;
      _lastdirection = currentdirection;
      
      if (_ticklecount >= kmaxticklecount && self.state == uigesturerecognizerstatepossible) {
        self.state = uigesturerecognizerstateended;
        //nslog(@"自定义手势成功,将执行回调方法");
      }
    }
  }
}
 
- (void)touchesended:(nsset *)touches withevent:(uievent *)event {
  [self reset];
}
 
- (void)touchescancelled:(nsset *)touches withevent:(uievent *)event {
  [self reset];
}
 
@end

viewcontroller.h

?
1
2
3
4
5
6
7
8
9
#import <uikit/uikit.h>
#import "kmgesturerecognizer.h"
 
@interface viewcontroller : uiviewcontroller
@property (strong, nonatomic) uiimageview *imgv;
@property (strong, nonatomic) uiimageview *imgv2;
@property (strong, nonatomic) kmgesturerecognizer *customgesturerecognizer;
 
@end

viewcontroller.m

?
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#import "viewcontroller.h"
 
@interface viewcontroller ()
- (void)handlepan:(uipangesturerecognizer *)recognizer;
- (void)handlepinch:(uipinchgesturerecognizer *)recognizer;
- (void)handlerotation:(uirotationgesturerecognizer *)recognizer;
- (void)handletap:(uitapgesturerecognizer *)recognizer;
- (void)handlelongpress:(uilongpressgesturerecognizer *)recognizer;
- (void)handleswipe:(uiswipegesturerecognizer *)recognizer;
- (void)handlecustomgesturerecognizer:(kmgesturerecognizer *)recognizer;
 
- (void)bindpan:(uiimageview *)imgvcustom;
- (void)bindpinch:(uiimageview *)imgvcustom;
- (void)bindrotation:(uiimageview *)imgvcustom;
- (void)bindtap:(uiimageview *)imgvcustom;
- (void)bindlongpress:(uiimageview *)imgvcustom;
- (void)bindswipe;
- (void)bingcustomgesturerecognizer;
- (void)layoutui;
@end
 
@implementation viewcontroller
 
- (void)viewdidload {
  [super viewdidload];
  
  [self layoutui];
}
 
- (void)didreceivememorywarning {
  [super didreceivememorywarning];
  // dispose of any resources that can be recreated.
}
 
#pragma mark - 处理手势操作
/**
 * 处理拖动手势
 *
 * @param recognizer 拖动手势识别器对象实例
 */
- (void)handlepan:(uipangesturerecognizer *)recognizer {
  //视图前置操作
  [recognizer.view.superview bringsubviewtofront:recognizer.view];
  
  cgpoint center = recognizer.view.center;
  cgfloat cornerradius = recognizer.view.frame.size.width / 2;
  cgpoint translation = [recognizer translationinview:self.view];
  //nslog(@"%@", nsstringfromcgpoint(translation));
  recognizer.view.center = cgpointmake(center.x + translation.x, center.y + translation.y);
  [recognizer settranslation:cgpointzero inview:self.view];
  
  if (recognizer.state == uigesturerecognizerstateended) {
    //计算速度向量的长度,当他小于200时,滑行会很短
    cgpoint velocity = [recognizer velocityinview:self.view];
    cgfloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
    cgfloat slidemult = magnitude / 200;
    //nslog(@"magnitude: %f, slidemult: %f", magnitude, slidemult); //e.g. 397.973175, slidemult: 1.989866
    
    //基于速度和速度因素计算一个终点
    float slidefactor = 0.1 * slidemult;
    cgpoint finalpoint = cgpointmake(center.x + (velocity.x * slidefactor),
                     center.y + (velocity.y * slidefactor));
    //限制最小[cornerradius]和最大边界值[self.view.bounds.size.width - cornerradius],以免拖动出屏幕界限
    finalpoint.x = min(max(finalpoint.x, cornerradius),
              self.view.bounds.size.width - cornerradius);
    finalpoint.y = min(max(finalpoint.y, cornerradius),
              self.view.bounds.size.height - cornerradius);
    
    //使用 uiview 动画使 view 滑行到终点
    [uiview animatewithduration:slidefactor*2
               delay:0
              options:uiviewanimationoptioncurveeaseout
             animations:^{
               recognizer.view.center = finalpoint;
             }
             completion:nil];
  }
}
 
/**
 * 处理捏合手势
 *
 * @param recognizer 捏合手势识别器对象实例
 */
- (void)handlepinch:(uipinchgesturerecognizer *)recognizer {
  cgfloat scale = recognizer.scale;
  recognizer.view.transform = cgaffinetransformscale(recognizer.view.transform, scale, scale); //在已缩放大小基础下进行累加变化;区别于:使用 cgaffinetransformmakescale 方法就是在原大小基础下进行变化
  recognizer.scale = 1.0;
}
 
/**
 * 处理旋转手势
 *
 * @param recognizer 旋转手势识别器对象实例
 */
- (void)handlerotation:(uirotationgesturerecognizer *)recognizer {
  recognizer.view.transform = cgaffinetransformrotate(recognizer.view.transform, recognizer.rotation);
  recognizer.rotation = 0.0;
}
 
/**
 * 处理点按手势
 *
 * @param recognizer 点按手势识别器对象实例
 */
- (void)handletap:(uitapgesturerecognizer *)recognizer {
  uiview *view = recognizer.view;
  view.transform = cgaffinetransformmakescale(1.0, 1.0);
  view.transform = cgaffinetransformmakerotation(0.0);
  view.alpha = 1.0;
}
 
/**
 * 处理长按手势
 *
 * @param recognizer 点按手势识别器对象实例
 */
- (void)handlelongpress:(uilongpressgesturerecognizer *)recognizer {
  //长按的时候,设置不透明度为0.7
  recognizer.view.alpha = 0.7;
}
 
/**
 * 处理轻扫手势
 *
 * @param recognizer 轻扫手势识别器对象实例
 */
- (void)handleswipe:(uiswipegesturerecognizer *)recognizer {
  //代码块方式封装操作方法
  void (^positionoperation)() = ^() {
    cgpoint newpoint = recognizer.view.center;
    newpoint.y -= 20.0;
    _imgv.center = newpoint;
    
    newpoint.y += 40.0;
    _imgv2.center = newpoint;
  };
  
  //根据轻扫方向,进行不同控制
  switch (recognizer.direction) {
    case uiswipegesturerecognizerdirectionright: {
      positionoperation();
      break;
    }
    case uiswipegesturerecognizerdirectionleft: {
      positionoperation();
      break;
    }
    case uiswipegesturerecognizerdirectionup: {
      break;
    }
    case uiswipegesturerecognizerdirectiondown: {
      break;
    }
  }
}
 
/**
 * 处理自定义手势
 *
 * @param recognizer 自定义手势识别器对象实例
 */
- (void)handlecustomgesturerecognizer:(kmgesturerecognizer *)recognizer {
  //代码块方式封装操作方法
  void (^positionoperation)() = ^() {
    cgpoint newpoint = recognizer.view.center;
    newpoint.x -= 20.0;
    _imgv.center = newpoint;
    
    newpoint.x += 40.0;
    _imgv2.center = newpoint;
  };
  
  positionoperation();
}
 
 
#pragma mark - 绑定手势操作
/**
 * 绑定拖动手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
- (void)bindpan:(uiimageview *)imgvcustom {
  uipangesturerecognizer *recognizer = [[uipangesturerecognizer alloc] initwithtarget:self
                                         action:@selector(handlepan:)];
  [imgvcustom addgesturerecognizer:recognizer];
}
 
/**
 * 绑定捏合手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
- (void)bindpinch:(uiimageview *)imgvcustom {
  uipinchgesturerecognizer *recognizer = [[uipinchgesturerecognizer alloc] initwithtarget:self
                                           action:@selector(handlepinch:)];
  [imgvcustom addgesturerecognizer:recognizer];
  //[recognizer requiregesturerecognizertofail:imgvcustom.gesturerecognizers.firstobject];
}
 
/**
 * 绑定旋转手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
- (void)bindrotation:(uiimageview *)imgvcustom {
  uirotationgesturerecognizer *recognizer = [[uirotationgesturerecognizer alloc] initwithtarget:self
                                              action:@selector(handlerotation:)];
  [imgvcustom addgesturerecognizer:recognizer];
}
 
/**
 * 绑定点按手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
- (void)bindtap:(uiimageview *)imgvcustom {
  uitapgesturerecognizer *recognizer = [[uitapgesturerecognizer alloc] initwithtarget:self
                                         action:@selector(handletap:)];
  //使用一根手指双击时,才触发点按手势识别器
  recognizer.numberoftapsrequired = 2;
  recognizer.numberoftouchesrequired = 1;
  [imgvcustom addgesturerecognizer:recognizer];
}
 
/**
 * 绑定长按手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
- (void)bindlongpress:(uiimageview *)imgvcustom {
  uilongpressgesturerecognizer *recognizer = [[uilongpressgesturerecognizer alloc] initwithtarget:self action:@selector(handlelongpress:)];
  recognizer.minimumpressduration = 0.5; //设置最小长按时间;默认为0.5秒
  [imgvcustom addgesturerecognizer:recognizer];
}
 
/**
 * 绑定轻扫手势;支持四个方向的轻扫,但是不同的方向要分别定义轻扫手势
 */
- (void)bindswipe {
  //向右轻扫手势
  uiswipegesturerecognizer *recognizer = [[uiswipegesturerecognizer alloc] initwithtarget:self
                                           action:@selector(handleswipe:)];
  recognizer.direction = uiswipegesturerecognizerdirectionright; //设置轻扫方向;默认是 uiswipegesturerecognizerdirectionright,即向右轻扫
  [self.view addgesturerecognizer:recognizer];
  [recognizer requiregesturerecognizertofail:_customgesturerecognizer]; //设置以自定义挠痒手势优先识别
  
  //向左轻扫手势
  recognizer = [[uiswipegesturerecognizer alloc] initwithtarget:self
                              action:@selector(handleswipe:)];
  recognizer.direction = uiswipegesturerecognizerdirectionleft;
  [self.view addgesturerecognizer:recognizer];
  [recognizer requiregesturerecognizertofail:_customgesturerecognizer]; //设置以自定义挠痒手势优先识别
}
 
/**
 * 绑定自定义挠痒手势;判断是否有三次不同方向的动作,如果有则手势结束,将执行回调方法
 */
- (void)bingcustomgesturerecognizer {
  //当 recognizer.state 为 uigesturerecognizerstateended 时,才执行回调方法 handlecustomgesturerecognizer:
  
  //_customgesturerecognizer = [kmgesturerecognizer new];
  _customgesturerecognizer = [[kmgesturerecognizer alloc] initwithtarget:self
                                  action:@selector(handlecustomgesturerecognizer:)];
  [self.view addgesturerecognizer:_customgesturerecognizer];
}
 
- (void)layoutui {
  //图片视图 _imgv
  uiimage *img = [uiimage imagenamed:@"emoticon_tusiji_icon"];
  cgfloat cornerradius = img.size.width;
  _imgv = [[uiimageview alloc] initwithimage:img];
  _imgv.frame = cgrectmake(20.0, 20.0,
               cornerradius * 2, cornerradius * 2);
  _imgv.userinteractionenabled = yes;
  _imgv.layer.maskstobounds = yes;
  _imgv.layer.cornerradius = cornerradius;
  _imgv.layer.borderwidth = 2.0;
  _imgv.layer.bordercolor = [uicolor graycolor].cgcolor;
  [self.view addsubview:_imgv];
  
  //图片视图 _imgv2
  img = [uiimage imagenamed:@"emoticon_tusiji_icon2"];
  cornerradius = img.size.width;
  _imgv2 = [[uiimageview alloc] initwithimage:img];
  _imgv2.frame = cgrectmake(20.0, 40.0 + _imgv.frame.size.height,
               cornerradius * 2, cornerradius * 2);
  _imgv2.userinteractionenabled = yes;
  _imgv2.layer.maskstobounds = yes;
  _imgv2.layer.cornerradius = cornerradius;
  _imgv2.layer.borderwidth = 2.0;
  _imgv2.layer.bordercolor = [uicolor orangecolor].cgcolor;
  [self.view addsubview:_imgv2];
  
  
  [self bindpan:_imgv];
  [self bindpinch:_imgv];
  [self bindrotation:_imgv];
  [self bindtap:_imgv];
  [self bindlongpress:_imgv];
  
  [self bindpan:_imgv2];
  [self bindpinch:_imgv2];
  [self bindrotation:_imgv2];
  [self bindtap:_imgv2];
  [self bindlongpress:_imgv2];
  
  //为了处理手势识别优先级的问题,这里需先绑定自定义挠痒手势
  [self bingcustomgesturerecognizer];
  [self bindswipe];
}
 
@end

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.cnblogs.com/huangjianwu/p/4675648.html