【IOS开发进阶系列】手势专题

1 touchesBegan手势

        iPhone中处理触摸屏的操作,在3.2之前是主要使用的是由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

2 UIGestureRecognizer

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

UITapGestureRecognizer

UIPinchGestureRecognizer

UIRotationGestureRecognizer

UISwipeGestureRecognizer

UIPanGestureRecognizer

UILongPressGestureRecognizer

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

Tap(点一下)

Pinch(二指往內或往外拨动,平时经常用到的缩放)

Rotation(旋转)

Swipe(滑动,快速移动)

Pan (拖移,慢速移动)

 LongPress(长按)

UIGestureRecognizer的继承关系如下:

2.1 使用手势的步骤

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

        创建手势实例。当创建手势时,指定一个回调方法,当手势开始,改变、或结束时,回调方法被调用。

        添加到需要识别的View中。每个手势只对应一个View,当屏幕触摸在View的边界内时,如果手势和预定的一样,那就会回调方法。

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

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

2.2 Pan 拖动手势

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,然后添加手势

回调方法:

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

}

2.3 Pinch缩放手势

UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget: self action: @selector(handlePinch:)];

[snakeImageView addGestureRecognizer: pinchGestureRecognizer];

UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]  initWithTarget: self action: @selector(handlePinch:)];

[snakeImageView addGestureRecognizer: pinchGestureRecognizer];


- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer

{

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

    recognizer.scale = 1;

}

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer

{

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

    recognizer.scale = 1;

}

2.4 Rotation旋转手势

UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget: self action: @selector(handleRotate:)];

[snakeImageView addGestureRecognizer: rotateRecognizer];

UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]  initWithTarget: self action: @selector(handleRotate:)];

[snakeImageView addGestureRecognizer: rotateRecognizer];


- (void) handleRotate: (UIRotationGestureRecognizer*) recognizer

{

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

    recognizer.rotation = 0;

}

- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer

{

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

    recognizer.rotation = 0;

}


        添加了这几个手势后,运行看效果,程序中的imageView放了一条蛇的图片,在模拟器上拖动是没问题的。缩放和旋转有点问题,估计是因为在模拟器上的模拟的两个接触点距离在imageView的边界外了,所以操作无效果。建议在真机上运行这个手势。

        在模拟器上缩放和选择的操作技巧:

        可以把imageView的frame值设置大一点,按住alt键,按下触摸板(不按下不行),这样就可以旋转和缩放了。

2.5 添加第二个ImagView并添加手势

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

- (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都能接收上面的三种手势。运行效果如下:


2.6 拖动(pan手势)速度(以较快的速度拖放后view有滑行的效果)

如何实现呢?

监视手势是否结束

监视触摸的速度

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

        floatslideFactor = 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还会在原来的方向滑行一段路。


2.7 同时触发两个view的手势

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

@interface ViewController : UIViewController


@end

@interface ViewController : UIViewController


@end

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

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

{

    return YES;

}

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

{

    return YES;

}

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

panGestureRecognizer.delegate = self;

pinchGestureRecognizer.delegate = self;

rotateRecognizer.delegate = self;

panGestureRecognizer.delegate = self;

pinchGestureRecognizer.delegate = self;

rotateRecognizer.delegate = self;

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

2.8 tap点击手势

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

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

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

}

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

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>


@interface ViewController : UIViewController

    @property (strong) AVAudioPlayer * chompPlayer;

    @property (strong) AVAudioPlayer * hehePlayer;    

@end

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

    [self.chompPlayer play];

}


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

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

2.9 手势的依赖性

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

        [tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];

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


2.10 自定义手势

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

– touchesBegan:withEvent:

– touchesMoved:withEvent:

– touchesEnded:withEvent:

- touchesCancelled:withEvent:

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

.h文件

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

#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

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

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

容芳志 (http://blog.csdn.net/totogo2010)


3 手势相关事件方法

        UIView关于手势的方法:

-(void) addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer  增加一个手势。

-(void) removeGestureRecognizer:(UIGestureRecognizer *)getureRecognizer 删除一个手势。

-(BOOL) gestureRecognizerShouldBegan:(UIGestureRecognizer *)gestureRecognizer 询问是否开始执行该手势,默认返回YES。

       手势相比触碰事件的好处是可以直接使用已经定义好的手势,开发者不用自己计算手指移动轨迹。

UIGestureRecognizer是一个手势基类,提供了简单的手势实现方式。衍生类如下:

UITabGestureRecognizer         轻击手势

UIPinchGestureRecognizer       捏合手势

UIRotationGestureRecognizer    旋转手势

UISwipeGestureRecognizer  轻扫手势

UIPanGestureRecognizer 拖拽手势

UILongPressGestrueRecognizer 长按手势

UIGestureRecognizer主要方法:

-(id) initWithTarget:action:初始化方法

-(void)addTarget:action:

-(void)removeTarget:action: 

        主要属性:

UIGestureRecognizerState state 手势识别当前状态

        有以下几种情况:

UIGestureRecognizerStatePossibel,  未识别状态

UIGestureRecognizerStateBegan,    手势开始

UIGestureRecognizerStateChanged,  手势改变

UIGestureRecognizerStateEnded, 手势结束

UIGestureRecognizerStateFailured 手势失败,被其他事件中断。

UITabGestureRecognizer  轻击手势任意手指任意次数的点击

属性:

numberOfTapsRequired 点击次数

numberOfTouchesRequired 手指个数

UIPinchGestureRecognizer  捏合或者扩张手势

属性:

scale:初始值为1,两手指距离减少则scale不断变小;两个手指重合则变为0;

velocity:初始值为0,手指移动的相对速度,两手指距离减少为负数,速度越快数值越少;两手指距离变大为整数,速度越快数值越大。

UIRotationGestureRecognizer 旋转手势

属性:

rotation:初始值为0,两手指的旋转弧度,顺时针旋转为正数,逆时针旋转为负数。

velocity:初始值为0手指一动的相对速度,顺时针为正数越快值越大;逆时针为负越快越小。

UISwipGestureRecognizer 轻扫手势,一个手势只能指定一个方向,如果需要指定多个方向需要多个手势

属性:

numberOfTouchesRequired: 手指个数

direction:手势方向,如UISwipeGestureRecognizerDirectionRight向右

UIPanGestureRecognizer:  拖拽手势,相比轻扫手势,手指与屏幕的交互时间更长。

属性:

mininumNumberOfTouches:默认值为1,最少手指数量

maxnumNumberOfTouches:最大手指数量

UILongPressGestrueRecognizer: 长按手势。

属性:

numberOfTapsRequired:默认值为0,轻击的次数。

numberOfTouchesRequired:默认值是1,手指数量。

mininumPressDuration:默认值为0.5,单位是秒。

allowableMovement:默认值为10,单位是像素。

4 开发技巧

4.1 要注意的问题

4.1.1 手势尽量不要全屏幕使用,以防截留其他事件

        添加手势后,手势响应事件是第一响应者,所以稍不注意,就容易截掉其他事件的响应。最好是,那一块需要手势,就用到哪一块;实在不行,记得取得响应后,把事件继续往事件响应链后面传递。


5 参考链接

iOS触摸事件处理

http://www.cnblogs.com/Quains/p/3369132.html


IOS中Touch事件传递

http://www.xnwai.com/2012/11/ios-touch-event-delivery.html


IOS应用事件的传递分析

http://blog.csdn.net/linux_zkf/article/details/7797881


IOS事件传递说明

http://blog.csdn.net/a15950711997/article/details/39369587


iOS开发UI篇—事件传递

http://www.cnblogs.com/wendingding/p/3795167.html


Responder Chain(ios事件传递)

http://blog.csdn.net/yongyinmg/article/details/19616527

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容