您的位置:首页 > 移动开发 > IOS开发

ios手势操作

2015-05-21 09:13 411 查看


一、概述

iPhone中处理触摸屏的操作,在3.2之前是主要使用的是由[b]UIResponder而来的如下4种方式:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

但是这种方式甄别不同的手势操作实在是麻烦,需要你自己计算做不同的手势分辨。后来。。。

苹果就给出了一个比较简便的方式,就是使用UIGestureRecognizer

二、UIGestureRecognizer

UIGestureRecognizer基类
是一个抽象类
,我们主要是使用它的子类(名字包含链接,可以点击跳到ios Developer library,看官方文档):

UITapGestureRecognizer


UIPinchGestureRecognizer


UIRotationGestureRecognizer


UISwipeGestureRecognizer


UIPanGestureRecognizer


UILongPressGestureRecognizer


从名字上我们就能知道,
Tap(点击)、Pinch(捏合)、Rotation(旋转)、Swipe(滑动,快速移动,是用于监测滑动的方向的)、Pan (拖移,慢速移动,是用于监测偏移的量的)以及 LongPress(长按)。

举个例子,可以在viewDidLoad函数里面添加:

[cpp] view
plaincopyprint?

-(void) viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view from its nib.

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];

[self.view addGestureRecognizer:panRecognizer];//关键语句,给self.view添加一个手势监测;

panRecognizer.maximumNumberOfTouches = 1;

panRecognizer.delegate = self;

[panRecognizer release];

}

其它手势方法类似。

其核心就是设置delegate和在需要手势监测的view上使用addGestureRecognizer添加指定的手势监测。

当然要记得在作为delegate的view的头文件加上<UIGestureRecognizerDelegate>。

不过有些手势是关联的,怎么办呢?例如 Tap 与 LongPress、Swipe与 Pan,或是 Tap 一次与Tap 兩次。

手势识别是具有互斥的原则的比如单击和双击,如果它识别出一种手势,其后的手势将不被识别。所以对于关联手势,要做特殊处理以帮助程序甄别,应该把当前手势归结到哪一类手势里面。

比如,单击和双击并存时,如果不做处理,它就只能发送出单击的消息。为了能够识别出双击手势,就需要做一个特殊处理逻辑,即先判断手势是否是双击,在双击失效的情况下作为单击手势处理。使用

[A requireGestureRecognizerToFail:B]函数,它可以指定当A手势发生时,即便A已经滿足条件了,也不会立刻触发会等到指定的手势B确定失败之后才触发。

[cpp] view
plaincopyprint?

- (void)viewDidLoad

{

// 单击的 Recognizer

UITapGestureRecognizer* singleRecognizer;

singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(SingleTap:)];

//点击的次数

singleTapRecognizer.numberOfTapsRequired = 1; // 单击

//给self.view添加一个手势监测;

[self.view addGestureRecognizer:singleRecognizer];

// 双击的 Recognizer

UITapGestureRecognizer* doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(DoubleTap:)];

doubleRecognizer.numberOfTapsRequired = 2; // 双击

//关键语句,给self.view添加一个手势监测;

[self.view addGestureRecognizer:doubleRecognizer];

// 关键在这一行,双击手势确定监测失败才会触发单击手势的相应操作

[singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];

[singleRecognizer release];

[doubleRecognizer release];

}

-(void)SingleTap:(UITapGestureRecognizer*)recognizer

{

//处理单击操作

}

-(void)DoubleTap:(UITapGestureRecognizer*)recognizer

{

//处理双击操作

}

三、iphone操作手势的大概种类

1.点击(Tap)

点击作为最常用手势,用于按下或选择一个控件或条目(类似于普通的鼠标点击)、

2.拖动(Drag)

拖动用于实现一些页面的滚动,以及对控件的移动功能。

3.滑动(Flick)

滑动用于实现页面的快速滚动和翻页的功能。

4.横扫(Swipe)

横扫手势用于激活列表项的快捷操作菜单

5.双击(Double Tap)

双击放大并居中显示图片,或恢复原大小(如果当前已经放大)。同时,双击能够激活针对文字编辑菜单。

6.放大(Pinch open)

放大手势可以实现以下功能:打开订阅源,打开文章的详情。在照片查看的时候,放大手势也可实现放大图片的功能。

7.缩小(Pinch close)

缩小手势,可以实现与放大手势相反且对应的功能的功能:关闭订阅源退出到首页,关闭文章退出至索引页。在照片查看的时候,缩小手势也可实现缩小图片的功能。

8.长按(Touch &Hold)

在我的订阅页,长按订阅源将自动进入编辑模式,同时选中手指当前按下的订阅源。这时可直接拖动订阅源移动位置。

针对文字长按,将出现放大镜辅助功能。松开后,则出现编辑菜单。

针对图片长按,将出现编辑菜单。

9.摇晃(Shake)

摇晃手势,将出现撤销与重做菜单。主要是针对用户文本输入的。

[/b]





1、UIGestureRecognizer介绍

手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。

iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了UIGestureRecognizer类。手势识别UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。

UITapGestureRecognizer
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UILongPressGestureRecognizer

上面的手势对应的操作是:

Tap(点一下)
Pinch(二指往內或往外拨动,平时经常用到的缩放)
Rotation(旋转)
Swipe(滑动,快速移动)
Pan (拖移,慢速移动)
LongPress(长按)

UIGestureRecognizer的继承关系如下:



2、使用手势的步骤

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

创建手势实例。当创建手势时,指定一个回调方法,当手势开始,改变、或结束时,回调方法被调用。
添加到需要识别的View中。每个手势只对应一个View,当屏幕触摸在View的边界内时,如果手势和预定的一样,那就会回调方法。

ps:一个手势只能对应一个View,但是一个View可以有多个手势。

建议在真机上运行这些手势,模拟器操作不太方便,可能导致你认为手势失效。

3、Pan 拖动手势:

[cpp] view
plaincopy

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,然后添加手势
回调方法:

[cpp] view
plaincopy

- (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缩放手势

[cpp] view
plaincopy

UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]

initWithTarget:self

action:@selector(handlePinch:)];<p class="p1">[<span class="s1">snakeImageView</span> <span class="s2">addGestureRecognizer</span>:pinchGestureRecognizer];</p>

[cpp] view
plaincopy

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer

{

recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);

recognizer.scale = 1;

}

5、Rotation旋转手势

[cpp] view
plaincopy

UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]

initWithTarget:self

action:@selector(handleRotate:)];

[snakeImageView addGestureRecognizer:rotateRecognizer];

[cpp] view
plaincopy

- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer

{

recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);

recognizer.rotation = 0;

}





添加了这几个手势后,运行看效果,程序中的imageView放了一个
/^\/^\
_|__| O|
\/ /~ \_/ \
\____|__________/ \
\_______ \
`\ \ \
| | \
/ / \
/ / \\
/ / \ \
/ / \ \
/ / _----_ \ \
/ / _-~ ~-_ | |
( ( _-~ _--_ ~-_ _/ |
\ ~-____-~ _-~ ~-_ ~-_-~ /
~-_ _-~ ~-_ _-~
~--______-~ ~-___-~
的图片,在模拟器上拖动是没问题的。缩放和旋转有点问题,估计是因为在模拟器上的模拟的两个接触点距离在imageView的边界外了,所以操作无效果。
建议在真机上运行这个手势。
在模拟器上缩放和选择的操作技巧:
可以把imageView的frame值设置大一点,按住alt键,按下触摸板(不按下不行),这样就可以旋转和缩放了。

6、添加第二个ImagView并添加手势

记住:一个手势只能添加到一个View,两个View当然要有两个手势的实例了

[cpp] view
plaincopy

- (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有滑行的效果)

如何实现呢?

监视手势是否结束
监视触摸的速度

[cpp] view
plaincopy

- (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滑动到终点

运行后,快速拖动图像view放开会看到view还会在原来的方向滑行一段路。

8、同时触发两个view的手势

手势之间是互斥的,如果你想同时触发蛇和龙的view,那么需要实现协议

UIGestureRecognizerDelegate,

[cpp] view
plaincopy

@interface ViewController : UIViewController<UIGestureRecognizerDelegate>

@end

并在协议这个方法里返回YES。

[cpp] view
plaincopy

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

{

return YES;

}

把self作为代理设置给手势:

[cpp] view
plaincopy

panGestureRecognizer.delegate = self;

pinchGestureRecognizer.delegate = self;

rotateRecognizer.delegate = self;

这样可以同时拖动或旋转缩放两个view了。

9、tap点击手势

这里为了方便看到tap的效果,当点击一下屏幕时,播放一个声音。

为了播放声音,我们加入AVFoundation.framework这个框架。

[cpp] view
plaincopy

- (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;

}

我会在最后例子代码给出完整代码,添加手势的步骤和前面一样的。

[cpp] view
plaincopy

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController<UIGestureRecognizerDelegate>

@property (strong) AVAudioPlayer * chompPlayer;

@property (strong) AVAudioPlayer * hehePlayer;

@end

[cpp] view
plaincopy

- (void)handleTap:(UITapGestureRecognizer *)recognizer {

[self.chompPlayer play];

}

运行,点一下某个图,就会播放一个咬东西的声音。

不过这个点击播放声音有点缺陷,就是在慢慢拖动的时候也会播放。这使得两个手势重合了。怎么解决呢?使用手势的:requireGestureRecognizerToFail方法。

10、手势的依赖性

在viewDidLoad的循环里添加这段代码:

[cpp] view
plaincopy

[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];

意思就是,当如果pan手势失败,就是没发生拖动,才会出发tap手势。这样如果你有轻微的拖动,那就是pan手势发生了。tap的声音就不会发出来了。

11、自定义手势

自定义手势继承:UIGestureRecognizer,实现下面的方法:

[cpp] view
plaincopy

– touchesBegan:withEvent:

– touchesMoved:withEvent:

– touchesEnded:withEvent:

- touchesCancelled:withEvent:

新建一个类,继承UIGestureRecognizer,代码如下:

.h文件

[cpp] view
plaincopy

#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文件

[cpp] view
plaincopy

#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

调用自定义手势和上面一样,回到这样写:

[cpp] view
plaincopy

- (void)handleHappy:(HappyGestureRecognizer *)recognizer{

[self.hehePlayer play];

}

手势成功后播放呵呵笑的声音。

在真机上运行,按住某个view,快速左右拖动,就会发出笑的声音了。

代码解析:
先获取起始坐标:curTickleStart
通过和ticklePoint的x值对比,得出当前的放下是向左还是向右。再算出移动的x的值是否比MOVE_AMT_PER_TICKLE距离大,如果太则返回。
再判断是否有三次是不同方向的动作,如果是则手势结束,回调。

参考:http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more

例子代码:http://download.csdn.net/detail/totogo2010/5094059
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: