iOS--基础知识--手势

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

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

UITapGestureRecognizer  
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UILongPressGestureRecognizer

上面的手势对应的操作是: 
Tap(点一下)
Pinch(二指往內或往外拨动,平时经常用到的缩放)
Rotation(旋转)
Swipe(滑动,快速移动)
Pan (拖移,慢速移动)
 LongPress(长按)
UIGestureRecognizer的继承关系如下:

2、使用手势的步骤
使用手势很简单,分为两步:

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

ps:一个手势只能对应一个View,但是一个View可以有多个手势。建议在真机上运行这些手势,模拟器操作不太方便,可能导致你认为手势失效。

3、Pan 拖动手势:
1.UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];  
2.snakeImageView.frame = CGRectMake(50, 50, 100, 160);  
3.UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]  
4.                                                initWithTarget:self  
5.                                                action:@selector(handlePan:)];      
6.[snakeImageView addGestureRecognizer:panGestureRecognizer];  
7.[self.view setBackgroundColor:[UIColor whiteColor]];  
8.[self.view addSubview:snakeImageView];

新建一个ImageView,然后添加手势
回调方法:
1.- (void) handlePan:(UIPanGestureRecognizer*) recognizer  
2.{  
3.    CGPoint translation = [recognizer translationInView:self.view];  
4.    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,  
5.                                   recognizer.view.center.y + translation.y);  
6.    [recognizer setTranslation:CGPointZero inView:self.view];  
7.      
8.}

4、Pinch缩放手势
1.UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]  
2.                                                        initWithTarget:self  
3.                                                        action:@selector(handlePinch:)];

[<span   class="s1">snakeImageView addGestureRecognizer:pinchGestureRecognizer];

1.- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer  
2.{  
3.    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);  
4.    recognizer.scale = 1;  
5.}

5、Rotation旋转手势
1.UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]  
2.                                                 initWithTarget:self  
3.                                                 action:@selector(handleRotate:)];  
4.[snakeImageView addGestureRecognizer:rotateRecognizer];

1.- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer  
2.{  
3.    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);  
4.    recognizer.rotation = 0;  
5.}

添加了这几个手势后,运行看效果,程序中的imageView放了一个这样的图片
                    /^\/^\
                  _|__|  O|
         \/     /~     \_/ \
          \____|__________/  \
                 \_______      \
                         `\     \                 \
                           |     |                  \
                          /      /                    \
                         /     /                       \\
                       /      /                         \ \
                      /     /                            \  \
                    /     /             _----_            \   \
                   /     /           _-~      ~-_         |   |
                  (      (        _-~    _--_    ~-_     _/   |
                   \      ~-____-~    _-~    ~-_    ~-_-~    /
                     ~-_           _-~          ~-_       _-~   
                        ~--______-~                ~-___-~
在模拟器上拖动是没问题的。缩放和旋转有点问题,估计是因为在模拟器上的模拟的两个接触点距离在imageView的边界外了,所以操作无效果。建议在真机上运行这个手势。

在模拟器上缩放和选择的操作技巧:可以把imageView的frame值设置大一点,按住alt键,按下触摸板(不按下不行),这样就可以旋转和缩放了。

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

多添加了一条龙的view,两个view都能接收上面的三种手势。运行效果如下:

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,
@interface ViewController : UIViewController  
@end

并在协议这个方法里返回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;  
}

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

1.#import    
2.#import    
3.  
[email protected] ViewController : UIViewController  
[email protected] (strong) AVAudioPlayer * chompPlayer;  
[email protected] (strong) AVAudioPlayer * hehePlayer;  
7.  
[email protected]

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

10、手势的依赖性

在viewDidLoad的循环里添加这段代码:
[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];

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

11、自定义手势
自定义手势继承:UIGestureRecognizer,实现下面的方法:
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:

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

.h文件

#import 
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    
#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

来源:容芳志的博客

时间: 2024-08-09 02:27:12

iOS--基础知识--手势的相关文章

iOS面试必备-iOS基础知识

近期为准备找工作面试,在网络上搜集了这些题,以备面试之用. 插一条广告:本人求职,2016级应届毕业生,有开发经验.可独立开发,低薪求职.QQ:895193543 1.简述OC中内存管理机制. 答:内存管理机制:使用引用计数管理,分为ARC和MRC,MRC需要程序员自己管理内存,ARC则不需要.但是并不是 所有对象在ARC环境下均不需要管理内存,子线程和循环引用并不是这样.与retain配对使用的是release,retain代表引用计 数+1,release代表引用计数-1,当引用计数减为0时

ios基础知识

1 1获取系统语言设置 2 3 NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; 4 5 NSArray *languages = [userDefault objectForKey:@"AppleLanguages"]; 6 7 NSString *preferredLang = [languages objectAtIndex:0]; 8 9 2 10 11 缓存路径下文件大小 12 13 14

IOS基础知识学习

第一章MAC  OS X 1.Mac操作系统,俗称雪豹系统,开发IPhone开发首先要安装MAC系统. 2.objective-c是基于C语言的扩展 3.Mac App store应用商店是苹果公司的电子市场,程序员开发的程序必须上传到此商店上,供别人下载. 4.Appkit用于MAC界面开发,Uikit用于IPhone界面开发. 5.Application kit框架包含实现图形,事件驱动等 6.Xcode是用于开发MAC OS 和IOS应用程序的实用工具,要熟练运用它. 7.Xcode提供代

ios基础知识--05

1.UIView的tag属性 /* 1.所有直接或者间接继承UIVIew的控件都有一个tag属性 2.这个属性,只能用来保存一个数字,对控件的外观没有任何影响 3.但是我们可以通过这个属性的值,来判断是哪个控件 */ 2.transform属性 /* 1. 可以使用动画,叫做变换 2. CGAffineTransformIdentity 如果赋值,那么之前通过transform属性进行的修改都会复原:_imageButton.transform= CGAffineTransformIdentit

iOS 基础知识

一.Objective-C语言特性有哪些? 1,c语言的超集,可以混编c和c++代码.(Objective-C++) 参考:http://blog.csdn.net/fengsh998/article/details/8010696 2,oc的方法调用为消息传递模型(用[]表示). 3,单继承.不支持内联.操作符重载.多继承. 4,Category.在不继承的基础上进行扩展,同时还可以对功能进行分组. 5,运行时机制.(method_setImplementation打补丁等等) 二.界面开发

iOS基础知识之类别

本类从三个方面介绍iOS中的类别,分别是  什么是类别:类别的语法:类别的作用.具体内容如下: 一.类别: 类的补丁:当不能获取现有类的源码,但需要对现有类的功能进行补充时,这种情况下使用类别. 类别只能添加方法,不能添加成员变量. 类别中不提倡使用@property,@property在类别中使用时,不能生成对应的私有变量,因为类别中不能声明成员变量. 例如:对NSString进行加密MD5,这种情况下不能获取NSString的源码,但需要为其添加加密功能,则可以使用类别实现. 二.类别语法

iOS基础知识之属性及属性关键字

iOS属性及属性关键字 一.属性功能:1.给现有的成员变量生成一对setter/getter方法.2.如果没有声明成员变量,自动声明一个_属性名的私有变量(默认的成员变量是受保护的). 二.属性关键字:assign 默认(缺省)关键字,基本数据类型的赋值.MRC:手动管理内存retain 对象的属性声明,保存引用计数,如果别的对象使用当前对象,则该对象的计数器加1,即两个对象同时指向同一块内存.copy 对象的属性声明,直接拷贝对象为一个新的副本,而被拷贝的对象的计数器不会加1,即两个对象分别指

IOS基础知识要点

第二章 Objective编程的基础 1.Objective-c是面向对象的开发语言,最早基于Smaltalk这门语言. 2.OC的基本数据类型分为int型float型bool类型double类型等 3.sel选择器通过一个叫做selector的选择器实现的 SEL 变量名=@selector(方法名): SEL 变量名=NSSelectorFromString(方法名的字符串) NSString *变量名=NSStringFromSelector(SEL参数) 4.私有字符串常量在.m和.mm

ios基础知识--03

设备 屏幕类型 屏幕尺寸 点 分辨率(像素) iPhone 3GS 非Retina 3.5 inch 320*480 320x480 iPhone4\4S Retina 3.5 inch 320*480 640x960 iPhone5\5C\5S Retina 4 inch 320*568 640x1136 iPhone6 Retina 4.7 inch 375*667 750x1334 iPhone6 Plus Retina 5.5 inch 414*736 1242x2208 在retina

iOS基础知识汇总(一)

一.通知 1.监听通知 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; 当anObject对象发布一条名字叫做aName的通知时,就会调用observer的aSelector方法 2.发布通知 // 发布一个通知对象(name.object.userInfo) - (void)postNotification:(NSNotification *