iOS--------手势识别的详细使用:拖动、缩放、旋转、点击、手势依赖、自定义手势
1、UIGestureRecognizer介绍
- UITapGestureRecognizer
- UIPinchGestureRecognizer
- UIRotationGestureRecognizer
- UISwipeGestureRecognizer
- UIPanGestureRecognizer
- UILongPressGestureRecognizer
上面的手势对应的操作是:
- Tap(点一下)
- Pinch(二指往內或往外拨动,平时经常用到的缩放)
- Rotation(旋转)
- Swipe(滑动,快速移动)
- Pan (拖移,慢速移动)
- LongPress(长按)

2、使用手势的步骤
- 创建手势实例。当创建手势时,指定一个回调方法,当手势开始,改变、或结束时,回调方法被调用。
- 添加到需要识别的View中。每个手势只对应一个View,当屏幕触摸在View的边界内时,如果手势和预定的一样,那就会回调方法。
3、Pan 拖动手势:
1
2
3
4
5
6
7
8
|
UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];
snakeImageView.frame = CGRectMake(50, 50, 100, 160);
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePan:)];
[snakeImageView addGestureRecognizer:panGestureRecognizer];
[self.view setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:snakeImageView];
|
新建一个ImageView,然后添加手势
1
2
3
4
5
6
7
8
|
- (void) handlePan:(UIPanGestureRecognizer*) recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self.view];
}
|
4、Pinch缩放手势
1
2
3
|
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePinch:)];<p class="p1">[<span class="s1">snakeImageView</span> <span class="s2">addGestureRecognizer</span>:pinchGestureRecognizer];</p>
|
1
2
3
4
5
|
- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
{
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
}
|
5、Rotation旋转手势
1
2
3
4
|
UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleRotate:)];
[snakeImageView addGestureRecognizer:rotateRecognizer];
|
1
2
3
4
5
|
- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer
{
recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
recognizer.rotation = 0;
}
|
6、添加第二个ImagView并添加手势
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
|
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];
UIImageView *dragonImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dragon.png"]];
snakeImageView.frame = CGRectMake(120, 120, 100, 160);
dragonImageView.frame = CGRectMake(50, 50, 100, 160);
[self.view addSubview:snakeImageView];
[self.view addSubview:dragonImageView];
for (UIView *view in self.view.subviews) {
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePan:)];
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePinch:)];
UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleRotate:)];
[view addGestureRecognizer:panGestureRecognizer];
[view addGestureRecognizer:pinchGestureRecognizer];
[view addGestureRecognizer:rotateRecognizer];
[view setUserInteractionEnabled:YES];
}
[self.view setBackgroundColor:[UIColor whiteColor]];
}
|
多添加了一条龙的view,两个view都能接收上面的三种手势。运行效果如下:

7、拖动(pan手势)速度(以较快的速度拖放后view有滑行的效果)
- 监视手势是否结束
- 监视触摸的速度
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
|
- (void) handlePan:(UIPanGestureRecognizer*) recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
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);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
[UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
|
代码实现解析:
- 计算速度向量的长度(估计大部分都忘了)这些知识了。
- 如果速度向量小于200,那就会得到一个小于的小数,那么滑行会很短
- 基于速度和速度因素计算一个终点
- 确保终点不会跑出父View的边界
- 使用UIView动画使view滑动到终点
8、同时触发两个view的手势
1
2
|
@interface ViewController : UIViewController<UIGestureRecognizerDelegate>
@end
|
并在协议这个方法里返回YES。
1
2
3
4
|
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
|
把self作为代理设置给手势:
1
2
3
|
panGestureRecognizer.delegate = self;
pinchGestureRecognizer.delegate = self;
rotateRecognizer.delegate = self;
|
这样可以同时拖动或旋转缩放两个view了。
9、tap点击手势
这里为了方便看到tap的效果,当点击一下屏幕时,播放一个声音。
为了播放声音,我们加入AVFoundation.framework这个框架。
1
2
3
4
5
6
7
8
9
10
11
|
- (AVAudioPlayer *)loadWav:(NSString *)filename {
NSURL * url = [[NSBundle mainBundle] URLForResource:filename withExtension:@"wav"];
NSError * error;
AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (!player) {
NSLog(@"Error loading %@: %@", url, error.localizedDescription);
} else {
[player prepareToPlay];
}
return player;
}
|
我会在最后例子代码给出完整代码,添加手势的步骤和前面一样的。
1
2
3
4
5
6
7
8
|
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController<UIGestureRecognizerDelegate>
@property (strong) AVAudioPlayer * chompPlayer;
@property (strong) AVAudioPlayer * hehePlayer;
@end
|
1
2
3
|
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
[self.chompPlayer play];
}
|
运行,点一下某个图,就会播放一个咬东西的声音。
不过这个点击播放声音有点缺陷,就是在慢慢拖动的时候也会播放。这使得两个手势重合了。怎么解决呢?使用手势的:requireGestureRecognizerToFail方法。
10、手势的依赖性
在viewDidLoad的循环里添加这段代码:
1
|
[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];
|
意思就是,当如果pan手势失败,就是没发生拖动,才会出发tap手势。这样如果你有轻微的拖动,那就是pan手势发生了。tap的声音就不会发出来了。
11、自定义手势
自定义手势继承:UIGestureRecognizer,实现下面的方法:
1
2
3
4
|
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:
|
新建一个类,继承UIGestureRecognizer,代码如下:
.h文件
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#import <UIKit/UIKit.h>
typedef enum {
DirectionUnknown = 0,
DirectionLeft,
DirectionRight
} Direction;
@interface HappyGestureRecognizer : UIGestureRecognizer
@property (assign) int tickleCount;
@property (assign) CGPoint curTickleStart;
@property (assign) Direction lastDirection;
@end
|
.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
|
#import "HappyGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
#define REQUIRED_TICKLES 2
#define MOVE_AMT_PER_TICKLE 25
@implementation HappyGestureRecognizer
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
self.curTickleStart = [touch locationInView:self.view];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// Make sure we've moved a minimum amount since curTickleStart
UITouch * touch = [touches anyObject];
CGPoint ticklePoint = [touch locationInView:self.view];
CGFloat moveAmt = ticklePoint.x - self.curTickleStart.x;
Direction curDirection;
if (moveAmt < 0) {
curDirection = DirectionLeft;
} else {
curDirection = DirectionRight;
}
if (ABS(moveAmt) < MOVE_AMT_PER_TICKLE) return;
// 确认方向改变了
if (self.lastDirection == DirectionUnknown ||
(self.lastDirection == DirectionLeft && curDirection == DirectionRight) ||
(self.lastDirection == DirectionRight && curDirection == DirectionLeft)) {
// 挠痒次数
self.tickleCount++;
self.curTickleStart = ticklePoint;
self.lastDirection = curDirection;
// 一旦挠痒次数超过指定数,设置手势为结束状态
// 这样回调函数会被调用。
if (self.state == UIGestureRecognizerStatePossible && self.tickleCount > REQUIRED_TICKLES) {
[self setState:UIGestureRecognizerStateEnded];
}
}
}
- (void)reset {
self.tickleCount = 0;
self.curTickleStart = CGPointZero;
self.lastDirection = DirectionUnknown;
if (self.state == UIGestureRecognizerStatePossible) {
[self setState:UIGestureRecognizerStateFailed];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self reset];
}
@end
|
调用自定义手势和上面一样,回到这样写:
1
2
3
|
- (void)handleHappy:(HappyGestureRecognizer *)recognizer{
[self.hehePlayer play];
}
|
手势成功后播放呵呵笑的声音。
在真机上运行,按住某个view,快速左右拖动,就会发出笑的声音了。
iOS--------手势识别的详细使用:拖动、缩放、旋转、点击、手势依赖、自定义手势的更多相关文章
- iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势)
iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势) 1.UIGestureRecognizer介绍 手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加 ...
- ios iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势)
iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势) 转自容芳志大神的博客:http://www.cnblogs.com/stoic/archive/2013/02/27/2940 ...
- 【转】iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势) -- 不错不错
原文网址:http://blog.csdn.net/totogo2010/article/details/8615940 1.UIGestureRecognizer介绍 手势识别在iOS上非常重要,手 ...
- 【iOS发展-89】UIGestureRecognizer完整的旋转手势识别、缩放和拖拽等效果
(1)效果 (2)代码 http://download.csdn.net/detail/wsb200514/8261001 (3)总结 --先依据所需创建不同类型的手势识别.比方: UITapGest ...
- IOS手势识别,捏合,旋转,轻扫等
ref:http://blog.csdn.net/rechard_chen/article/details/51769972 //点按手势的创建,这里需要实现响应事件的方法 UITapGestur ...
- iOS,手势识别简单使用
1.iOS目前支持的手势识别(6种) 2.点按手势和慢速拖动手势简单使用 iOS目前支持的手势识别(6种) UITapGestureRecognizer(点按) UIPinchGestureRecog ...
- UIGestureRecognizer ios手势识别温习
1.UIGestureRecognizer介绍 手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性. iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了 ...
- iOS 手势识别
首先给大家解释一下为什么要学习手势识别? 如果想监听一个UIView上面的触摸事件,之前的做法是: 自定义一个UIView : 实现UIView的touches方法,在方法里面实现具体功能 透过tou ...
- iOS手势识别
一.手势识别与触摸事件 1.如果想监听一个view上面的触摸事件,可选的做法是: (1)自定义一个view (2)实现view的touches方法,在方法内部实现具体处理代码 2.通过touches方 ...
随机推荐
- Vijos P1243 生产产品 (单调队列优化DP)
题意: 必须严格按顺序执行M个步骤来生产一个产品,每一个步骤都可以在N台机器中的任何一台完成.机器i完成第j个步骤的时间为T[i][j].把半成品从一台机器上搬到另一台机器上也需要一定的时间K.每台机 ...
- ansys-表格
转自http://blog.sina.com.cn/s/blog_833dee820102xwb3.html ANSYS中表格数组的定义及使用举例 ANSYS中会有许多的参数数据,这些参数的形成后要放 ...
- CodeForces 48C D - The Race (Fraction,数学)
每个加油的站可以确定一个alpha的上下界,比如,第i次加油站a[i],前面加了i次油,a[i]*10≤ alpha*i <(a[i]+1)*10. 取最大的下界,取最小的上界,看看两者之间的满 ...
- Android(java)学习笔记123:Android MediaPlayer 播放prepareAsync called in state 8解决办法
1. 使用android MediaPlayer播放音频文件时,有时会出现prepareasync called in state 8错误. 以下方法可以避免这个异常出现. 第1种方法: priva ...
- python3从尾到头打印链表
题目描述 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList. 方法一:通过栈实现 # -*- coding:utf-8 -*- # class ListNode: # def __ini ...
- WINDOWS-基础:SafeArray的使用方法
1 SafeArray的作用 使用SafeArray SafeArray是VB中的数组存储方式.通过SafeArray,可以在VC++和VB间相互调用. SafeArray也是Automation中的 ...
- 修改Windows默认调试器
程序崩溃时,系统会弹窗让你选择是否进行调试,可以设置系统默认调试器. 注册表位置: HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows NT/CurrentVe ...
- retain, copy, assign以及autorelease
一,retain, copy, assign区别 1. 假设你用malloc分配了一块内存,并且把它的地址赋值给了指针a,后来你希望指针b也共享这块内存,于是你又把a赋值给(assign)了b.此时a ...
- 微信iOS多设备多字体适配方案总结
一.背景 2014下半年,微信iOS版先后适配iPad, iPhone6/6plus.随着这些大屏设备的登场,部分用户觉得微信的字体太小,但也有很多用户不喜欢太大的字体.为了满足不同用户的需求,我们做 ...
- java中的jdbc操作
package demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedSta ...