IOS学习之 手势操作

参考文章 http://blog.jobbole.com/65846/

1. UIGestureRecognizer介绍

UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。

UITapGestureRecognizer                // 点击

    UIPinchGestureRecognizer            // 二指往內或往外拨动,平时经常用到的缩放

    UIRotationGestureRecognizer       // 旋转

    UISwipeGestureRecognizer           // 滑动,快速移动

    UIPanGestureRecognizer               // 拖移,慢速移动

    UILongPressGestureRecognizer   // 长按

2、使用手势的步骤

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

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

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

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

3、Pan 拖动手势:

// 新建一个ImageView,然后添加手势
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];
// 回调方法:
- (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缩放手势

UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]  
                                                        initWithTarget:self  
                                                        action:@selector(handlePinch:)];
- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer  {  
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);  
    recognizer.scale = 1;  
}

5、Rotation旋转手势

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

6、添加第二个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]];       
}

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

如何实现呢?

1.监视手势是否结束

2.监视触摸的速度

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

代码实现解析:

1.计算速度向量的长度(估计大部分都忘了)这些知识了。

2.如果速度向量小于200,那就会得到一个小于的小数,那么滑行会很短

3.基于速度和速度因素计算一个终点

4.确保终点不会跑出父View的边界

5.使用UIView动画使view滑动到终点

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

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

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

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

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {  
    return YES;  
}

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

panGestureRecognizer.delegate = self;  
pinchGestureRecognizer.delegate = self;  
rotateRecognizer.delegate = self;

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

9、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<UIGestureRecognizerDelegate>  
@property (strong) AVAudioPlayer * chompPlayer;  
@property (strong) AVAudioPlayer * hehePlayer;  
 @end
- (void)handleTap:(UITapGestureRecognizer *)recognizer {  
    [self.chompPlayer play];  
}

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

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

10、手势的依赖性

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

[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];

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

11、自定义手势

自定义手势继承: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距离大,如果太则返回。

再判断是否有三次是不同方向的动作,如果是则手势结束,回调。

时间: 2024-08-28 18:44:52

IOS学习之 手势操作的相关文章

蓝懿IOS学习七大手势Touches

今天学习了ios编程里手势的方法及应用场景,屏幕页面中区分很多控件,有的控件可以有点击事件和用户直接交互,可以执行相应方法,如TextField,Button,UISEgmentControll等,但是静态lableUIImageView等就需要把交互开关打开,添加响应的手势才能实现交互. 刘国斌老师详细的对我们讲了七大手势,包括点击Touches,UIPanGestureRecognizer拖动,UILongPressGestureRecognizer长按手势,UIScreenEdgePanG

iOS学习之手势

UIGestureRecognizer 为了完成手势识别,必须借助于手势识别器--UIGestureRecognizer,利用UIGestureRecognizer,能轻松识别用户在某个view上面做的一些常见手势UIGestureRecognizer是一个抽象类,定义了所有手势的基本行为,使用它的子类才能处理具体的手势,要实现<UIGestureRecognizerDelegate> 手势状态: typedef NS_ENUM(NSInteger, UIGestureRecognizerSt

iOS学习笔记——文件操作(NSFileManager)

iOS的沙盒机制,应用只能访问自己应用目录下的文件.iOS不像android,没有SD卡概念,不能直接访问图像.视频等内容.iOS应用产生的内容,如图像.文件.缓存内容等都必须存储在自己的沙盒内.默认情况下,每个沙盒含有3个文件夹:Documents, Library 和 tmp.Library包含Caches.Preferences目录.               上面的完整路径为:用户->资源库->Application Support->iPhone Simulator->

我的IOS学习之路(三):手势识别器

在iOS的学习中,对于手势的处理是极为重要的,如对于图片,我们经常需要进行旋转,缩放以及移动等.这里做一下总结,详见代码. 1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 UIImage *image = [UIImage imageNamed:@"018.png"]; 5 UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 6 imageView.

iOS开发——仿Clear纯手势操作的UITableView

前言 在Clear应用中,用户无需任何按钮,纯靠不同的手势就可以完成对ToDoItem的删除.完成.添加.移动.具体来说,功能上有左划删除,右划完成,点击编辑,下拉添加.捏合添加.长按移动.这里将这些功能实现并记录. 左划删除与右划完成 所谓的左右滑动,就是自定义一个cell然后在上面添加滑动手势.在处理方法中计算偏移量,如果滑动距离超过cell宽度一半,就删除它,或者是为文本添加删除线等来完成它:如果没有超过一半,那么就用动画把cell归位. 效果图如下: 关键代码如下: - (void)ha

iOS手势操作,拖动,轻击,捏合,旋转,长按,自定义(http://www.cnblogs.com/huangjianwu/p/4675648.html)

1.UIGestureRecognizer 介绍 手势识别在 iOS 中非常重要,他极大地提高了移动设备的使用便捷性. iOS 系统在 3.2 以后,他提供了一些常用的手势(UIGestureRecognizer 的子类),开发者可以直接使用他们进行手势操作. UIPanGestureRecognizer(拖动) UIPinchGestureRecognizer(捏合) UIRotationGestureRecognizer(旋转) UITapGestureRecognizer(点按) UILo

iOS学习之iOS沙盒(sandbox)机制和文件操作复习

1.iOS沙盒机制 iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等. 1.1.每个应用程序都有自己的存储空间 1.2.应用程序不能翻过自己的围墙去访问别的存储空间的内容 1.3.应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会被放行.     通过这张图只能从表层上理解sandbox是一种安全体系,应用程序的所有操作都要通过这个体系来执行,其中核心内容是

iOS学习之iOS沙盒(sandbox)机制和文件操作

iOS学习之iOS沙盒(sandbox)机制和文件操作(一) 1.iOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等. 1.1.每个应用程序都有自己的存储空间 1.2.应用程序不能翻过自己的围墙去访问别的存储空间的内容 1.3.应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会被放行. 通过这张图只能从表层上理解sandbox是一种安全体系,应

ios的手势操作之UIGestureRecognizer

一.概述 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 *)