iPhone开发之手势识别

总共有六种手势识别:轻击手势(TapGestureRecognizer),轻扫手势 (SwipeGestureRecognizer), 长按手势(LongPressGestureRecognizer),  拖动手势(PanGestureRecognizer), 捏合手势(PinchGestureRecognizer),旋转手势(RotationGestureRecognizer);

其实这些手势用touche事件完全可以实现,苹果就是把常用的触摸事件封装成手势,来提供给用户。读者完全可以用TouchesMoved来写拖动手势等。

一,用storyboard给控件添加手势识别

1.用storyboard添加手势识别,和添加一个Button的步骤一样,首先我们得找到相应的手势,把手势识别的控件拖到我们要添加手势的控件中,截图如下:

201048215652637.png

2.给我们拖出的手势添加回调事件,和给Button回调事件没啥区别的,在回调方法中添加要实现的业务逻辑即可,截图如下:

201056197849038.png

二,纯代码添加手势识别

用storyboard可以大大简化我们的操作,不过纯代码的方式还是要会的,就像要Dreamwear编辑网页一样(当然啦,storyboard的拖拽功能要比Dreamwear的拖拽强大的多),用纯代码敲出来的更为灵活,更加便 于维护。不过用storyboard可以减少我们的工作量,这两个要配合着使用才能大大的提高我们的开发效率。个人感觉用storyboard把框架搭起 来(Controller间的关系),一下小的东西还是用纯代码敲出来更好一些。下面就给出如何给我们的控件用纯代码的方式来添加手势识别。

1.轻击手势(TapGestureRecognizer)的添加

初始化代码TapGestureRecongnizer的代码如下:

//新建tap手势

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];

//设置点击次数和点击手指数

tapGesture.numberOfTapsRequired = 1; //点击次数

tapGesture.numberOfTouchesRequired = 1; //点击手指数

[self.view addGestureRecognizer:tapGesture];

在回调方法中添加相应的业务逻辑:

//轻击手势触发方法

-(void)tapGesture:(id)sender

{

//轻击后要做的事情       

}

2.长按手势(LongPressGestureRecognizer)
初始化代码:

//添加长摁手势

UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];

//设置长按时间

longPressGesture.minimumPressDuration = 0.5; //(2秒)

[self.view addGestureRecognizer:longPressGesture];

在对应的回调方法中添加相应的方法(当手势开始时执行):

//常摁手势触发方法

-(void)longPressGesture:(id)sender

{

UILongPressGestureRecognizer *longPress = sender;

if (longPress.state == UIGestureRecognizerStateBegan)

{

UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"长按触发" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil];

[alter show];

}

}

代码说明:手势的常用状态如下:

  • 开始:UIGestureRecognizerStateBegan

  • 改变:UIGestureRecognizerStateChanged

  • 结束:UIGestureRecognizerStateEnded

  • 取消:UIGestureRecognizerStateCancelled

  • 失败:UIGestureRecognizerStateFailed

3.轻扫手势(SwipeGestureRecognizer)

在初始化轻扫手势的时候得指定轻扫的方向,上下左右。 如果要要添加多个轻扫方向,就得添加多个轻扫手势,不过回调的是同一个方法。

添加轻扫手势,一个向左一个向右,代码如下:

//添加轻扫手势

UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];

//设置轻扫的方向

swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //默认向右

[self.view addGestureRecognizer:swipeGesture];

//添加轻扫手势

UISwipeGestureRecognizer *swipeGestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];

//设置轻扫的方向

swipeGestureLeft.direction = UISwipeGestureRecognizerDirectionLeft; //默认向右

[self.view addGestureRecognizer:swipeGestureLeft];

回调方法如下:

//轻扫手势触发方法

-(void)swipeGesture:(id)sender

{

UISwipeGestureRecognizer *swipe = sender;

if (swipe.direction == UISwipeGestureRecognizerDirectionLeft)

{

//向左轻扫做的事情

}

if (swipe.direction == UISwipeGestureRecognizerDirectionRight)

{

//向右轻扫做的事情

}

}

4.捏合手势(PinchGestureRecognizer)

捏合手势初始化

//添加捏合手势

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

[self.view addGestureRecognizer:pinchGesture];

捏合手势要触发的方法(放大或者缩小图片):

////捏合手势触发方法

-(void) pinchGesture:(id)sender

{

UIPinchGestureRecognizer *gesture = sender;

//手势改变时

if (gesture.state == UIGestureRecognizerStateChanged)

{

//捏合手势中scale属性记录的缩放比例

_imageView.transform = CGAffineTransformMakeScale(gesture.scale, gesture.scale);

}

//结束后恢复

if(gesture.state==UIGestureRecognizerStateEnded)

{

[UIView animateWithDuration:0.5 animations:^{

_imageView.transform = CGAffineTransformIdentity;//取消一切形变

}];

}

}

5.拖动手势(PanGestureRecognizer)

拖动手势的初始化

//添加拖动手势

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

[self.view addGestureRecognizer:panGesture];

拖动手势要做的方法(通过translationInView获取移动的点,和TouchesMoved方法类似)

//拖动手势

-(void) panGesture:(id)sender

{

UIPanGestureRecognizer *panGesture = sender;

CGPoint movePoint = [panGesture translationInView:self.view];

//做你想做的事儿

}

6.旋转手势(RotationGestureRecognizer)

旋转手势的初始化

//添加旋转手势

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

[self.view addGestureRecognizer:rotationGesture];

旋转手势调用的方法:

//旋转手势

-(void)rotationGesture:(id)sender

{

UIRotationGestureRecognizer *gesture = sender;

if (gesture.state==UIGestureRecognizerStateChanged)

{

_imageView.transform=CGAffineTransformMakeRotation(gesture.rotation);

}

if(gesture.state==UIGestureRecognizerStateEnded)

{

[UIView animateWithDuration:1 animations:^{

_imageView.transform=CGAffineTransformIdentity;//取消形变

}];

}

}

补充:

使用手势识别

六种手势识别(继承于UIGestureRecongnizer基类):

UITapGestureRecongnizer--检测view上的单击操作

UIPinchGestureRecongnizer--检测view上两个手指的缩放操作

UIPanGestureRecongnizer--检测view的拖拽操作

UISwipeGestureRecongnizer--检测view的轻划操作

UIRotationGestureRecongnizer--检测view的旋转操作

UILongPressGestureRecongnizer-检测view上的长按操作

UITapGestureRecongnizer 检测view上的单击操作

新建Empty Application项目,在xib中添加ImageView控件,Mode为Aspect Fit,选中User Interaction Enabled和Multiple Touch

HomeViewController.h

#import <UIKit/UIKit.h>

@interface HomeViewController : UIViewController

@property (retain, nonatomic) IBOutlet UIImageView *imageView;

@end

HomeViewController.m

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

- (void)viewDidLoad

{

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (void)dealloc {

[imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

  [self setImageView:nil];

    [super viewDidUnload];

}

@end

UIPinchGestureRecongnizer  检测view上两个手指的缩放操作

HomeViewController.m

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat lastScaleValue = 1;

- (void)viewDidLoad

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

    tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureHandler:)];

    [imageView addGestureRecognizer:pinchGesture];

    [pinchGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (IBAction)pinchGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat scaleValue = [(UIPinchGestureRecognizer *)sender scale];

//如果手指做放大操作,scaleValue的值大于等于1;如果手指是缩小操作,scaleValue的值小于1

    if (scaleValue > 1) {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue + (scaleValue-1), lastScaleValue + (scaleValue-1));

    }else {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue * scaleValue, lastScaleValue * scaleValue);

    }

//用户的手指离开了屏幕,将比例值记录在 lastScaleValue 变量中

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (scaleValue > 1) {

            lastScaleValue += (scaleValue - 1);

        }else {

            lastScaleValue += scaleValue;

        }

    }

}

- (void)dealloc {

    [imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

    [self setImageView:nil];

    [super viewDidUnload];

}

@end

UIRotationGestureRecongnizer  检测view的旋转操作

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat lastScaleValue = 1;

CGFloat rotationValue;

- (void)viewDidLoad

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

    tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureHandler:)];

    [imageView addGestureRecognizer:pinchGesture];

    [pinchGesture release];

UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureHandler:)];

    [imageView addGestureRecognizer:rotationGesture];

    [rotationGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (IBAction)pinchGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat scaleValue = [(UIPinchGestureRecognizer *)sender scale];

    if (scaleValue > 1) {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue + (scaleValue-1), lastScaleValue + (scaleValue-1));

    }else {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue * scaleValue, lastScaleValue * scaleValue);

    }

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (scaleValue > 1) {

            lastScaleValue += (scaleValue - 1);

        }else {

            lastScaleValue += scaleValue;

        }

    }

}

- (IBAction)rotationGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat rotation = [(UIRotationGestureRecognizer *)sender rotation];

    CGAffineTransform transform = CGAffineTransformMakeRotation(rotation + rotationValue);

    sender.view.transform = transform;

    if (sender.state == UIGestureRecognizerStateEnded) {

        rotationValue += rotation;

    }

}

- (void)dealloc {

    [imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

    [self setImageView:nil];

    [super viewDidUnload];

}

@end

UIPanGestureRecongnizer  检测view的拖拽操作

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat lastScaleValue = 1;

CGFloat rotationValue;

CGPoint positionValue;

- (void)viewDidLoad

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

    tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureHandler:)];

    [imageView addGestureRecognizer:pinchGesture];

    [pinchGesture release];

    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureHandler:)];

    [imageView addGestureRecognizer:rotationGesture];

    [rotationGesture release];

  UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];

    [imageView addGestureRecognizer:panGesture];

    [panGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (IBAction)pinchGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat scaleValue = [(UIPinchGestureRecognizer *)sender scale];

    if (scaleValue > 1) {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue + (scaleValue-1), lastScaleValue + (scaleValue-1));

    }else {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue * scaleValue, lastScaleValue * scaleValue);

    }

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (scaleValue > 1) {

            lastScaleValue += (scaleValue - 1);

        }else {

            lastScaleValue += scaleValue;

        }

    }

}

- (IBAction)rotationGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat rotation = [(UIRotationGestureRecognizer *)sender rotation];

    CGAffineTransform transform = CGAffineTransformMakeRotation(rotation + rotationValue);

    sender.view.transform = transform;

    if (sender.state == UIGestureRecognizerStateEnded) {

        rotationValue += rotation;

    }

}

- (IBAction)panGestureHandler:(UIGestureRecognizer *)sender{

    CGPoint position = [(UIPanGestureRecognizer *)sender translationInView:imageView];

    sender.view.transform = CGAffineTransformMakeTranslation(position.x + position.x,

                                                             position.y + position.y);

    if (sender.state == UIGestureRecognizerStateEnded) {

        positionValue.x += position.x;

        positionValue.y += position.y;

    }

}

- (void)dealloc {

    [imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

    [self setImageView:nil];

    [super viewDidUnload];

}

@end

UISwipeGestureRecongnizer  检测view的轻划操作

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat lastScaleValue = 1;

CGFloat rotationValue;

CGPoint positionValue;

NSArray *images;

int imageIndex = 0;

- (void)viewDidLoad

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

    tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureHandler:)];

    [imageView addGestureRecognizer:pinchGesture];

    [pinchGesture release];

    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureHandler:)];

    [imageView addGestureRecognizer:rotationGesture];

    [rotationGesture release];

/*注释panGesture的拖拽操作,否则划动和拖拽操作会产生混淆

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];

    [imageView addGestureRecognizer:panGesture];

    [panGesture release];

    */

images = [[NSArray alloc] initWithObjects:@"iphone.png", @"mm.jpg", @"avatar.png", nil];

    //默认情况下是向右的手势划动

    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];

    [imageView addGestureRecognizer:swipeGesture];

    [swipeGesture release];

    //定义向左的手势划动

    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];

    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;

    [imageView addGestureRecognizer:swipeLeftGesture];

    [swipeLeftGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (IBAction)pinchGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat scaleValue = [(UIPinchGestureRecognizer *)sender scale];

    if (scaleValue > 1) {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue + (scaleValue-1), lastScaleValue + (scaleValue-1));

    }else {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue * scaleValue, lastScaleValue * scaleValue);

    }

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (scaleValue > 1) {

            lastScaleValue += (scaleValue - 1);

        }else {

            lastScaleValue += scaleValue;

        }

    }

}

- (IBAction)rotationGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat rotation = [(UIRotationGestureRecognizer *)sender rotation];

    CGAffineTransform transform = CGAffineTransformMakeRotation(rotation + rotationValue);

    sender.view.transform = transform;

    if (sender.state == UIGestureRecognizerStateEnded) {

        rotationValue += rotation;

    }

}

- (IBAction)panGestureHandler:(UIGestureRecognizer *)sender{

    CGPoint position = [(UIPanGestureRecognizer *)sender translationInView:imageView];

    sender.view.transform = CGAffineTransformMakeTranslation(position.x + position.x,

                                                             position.y + position.y);

    if (sender.state == UIGestureRecognizerStateEnded) {

        positionValue.x += position.x;

        positionValue.y += position.y;

    }

}

- (IBAction)swipeGestureHandler:(UIGestureRecognizer *)sender{

    UISwipeGestureRecognizerDirection direction =[(UISwipeGestureRecognizer *)sender direction];

    switch (direction) {

        case UISwipeGestureRecognizerDirectionUp:

            NSLog(@"向上划动");

            break;

            case UISwipeGestureRecognizerDirectionDown:

            NSLog(@"向下划动");

            break;

            case UISwipeGestureRecognizerDirectionLeft:

            imageIndex++;

            break;

            case UISwipeGestureRecognizerDirectionRight:

            imageIndex--;

            break;

            default:

            break;

    }

    imageIndex = (imageIndex < 0) ? ([images count] - 1):imageIndex % [images count];

    imageView.image = [UIImage imageNamed:[images objectAtIndex:imageIndex]];

}

- (void)dealloc {

[images release];

    [imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

    [self setImageView:nil];

    [super viewDidUnload];

}

@end

UILongPressGestureRecongnizer  检测view上的长按操作

添加UIActionSheetDelegate协议

HomeViewController.h

#import <UIKit/UIKit.h>

@interface HomeViewController : UIViewController

<UIActionSheetDelegate>{}

@property (retain, nonatomic) IBOutlet UIImageView *imageView;

@end

HomeViewController.m

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat lastScaleValue = 1;

CGFloat rotationValue;

CGPoint positionValue;

NSArray *images;

int imageIndex = 0;

- (void)viewDidLoad

{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];

    tapGesture.numberOfTapsRequired = 2;

    [imageView addGestureRecognizer:tapGesture];

    [tapGesture release];

    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureHandler:)];

    [imageView addGestureRecognizer:pinchGesture];

    [pinchGesture release];

    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureHandler:)];

    [imageView addGestureRecognizer:rotationGesture];

    [rotationGesture release];

    /*注释panGesture的拖拽操作,否则划动和拖拽操作会产生混淆

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];

    [imageView addGestureRecognizer:panGesture];

    [panGesture release];

    */

    images = [[NSArray alloc] initWithObjects:@"iphone.png", @"mm.jpg", @"avatar.png", nil];

    //默认情况下是向右的手势划动

    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];

    [imageView addGestureRecognizer:swipeGesture];

    [swipeGesture release];

    //定义向左的手势划动

    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureHandler:)];

    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;

    [imageView addGestureRecognizer:swipeLeftGesture];

    [swipeLeftGesture release];

//开始长按的内容部分

    UILongPressGestureRecognizer *longpressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpressGestureHandler:)];

    longpressGesture.minimumPressDuration = 1;

    longpressGesture.allowableMovement = 15;

    longpressGesture.numberOfTouchesRequired = 1;

    [imageView addGestureRecognizer:longpressGesture];

    [longpressGesture release];

    [super viewDidLoad];

}

- (IBAction)tapGestureHandler:(UIGestureRecognizer *)sender{

    if (sender.view.contentMode == UIViewContentModeScaleAspectFit) {

        sender.view.contentMode = UIViewContentModeScaleAspectFill;

    } else {

        sender.view.contentMode = UIViewContentModeScaleAspectFit;

    }

}

- (IBAction)pinchGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat scaleValue = [(UIPinchGestureRecognizer *)sender scale];

    if (scaleValue > 1) {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue + (scaleValue-1), lastScaleValue + (scaleValue-1));

    }else {

        sender.view.transform = CGAffineTransformMakeScale(lastScaleValue * scaleValue, lastScaleValue * scaleValue);

    }

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (scaleValue > 1) {

            lastScaleValue += (scaleValue - 1);

        }else {

            lastScaleValue += scaleValue;

        }

    }

}

- (IBAction)rotationGestureHandler:(UIGestureRecognizer *)sender{

    CGFloat rotation = [(UIRotationGestureRecognizer *)sender rotation];

    CGAffineTransform transform = CGAffineTransformMakeRotation(rotation + rotationValue);

    sender.view.transform = transform;

    if (sender.state == UIGestureRecognizerStateEnded) {

        rotationValue += rotation;

    }

}

- (IBAction)panGestureHandler:(UIGestureRecognizer *)sender{

    CGPoint position = [(UIPanGestureRecognizer *)sender translationInView:imageView];

    sender.view.transform = CGAffineTransformMakeTranslation(position.x + position.x,

                                                             position.y + position.y);

    if (sender.state == UIGestureRecognizerStateEnded) {

        positionValue.x += position.x;

        positionValue.y += position.y;

    }

}

- (IBAction)swipeGestureHandler:(UIGestureRecognizer *)sender{

    UISwipeGestureRecognizerDirection direction =[(UISwipeGestureRecognizer *)sender direction];

    switch (direction) {

        case UISwipeGestureRecognizerDirectionUp:

            NSLog(@"向上划动");

            break;

            case UISwipeGestureRecognizerDirectionDown:

            NSLog(@"向下划动");

            break;

            case UISwipeGestureRecognizerDirectionLeft:

            imageIndex++;

            break;

            case UISwipeGestureRecognizerDirectionRight:

            imageIndex--;

            break;

            default:

            break;

    }

    imageIndex = (imageIndex < 0) ? ([images count] - 1):imageIndex % [images count];

    imageView.image = [UIImage imageNamed:[images objectAtIndex:imageIndex]];

}

- (IBAction)longpressGestureHandler:(UIGestureRecognizer *)sender{

    if ([(UILongPressGestureRecognizer *)sender state] == UIGestureRecognizerStateBegan) {

        UIActionSheet *actionSheet = [[UIActionSheet alloc]

                                      initWithTitle:@"图片操作"

                                      delegate:self

                                      cancelButtonTitle:nil

                                      destructiveButtonTitle:nil

                                      otherButtonTitles:@"保存", @"复制", nil];

        [actionSheet showInView:self.view];

        [actionSheet release];

    }

}

- (void)dealloc {

    [images release];

    [imageView release];

    [super dealloc];

}

- (void)viewDidUnload {

    [self setImageView:nil];

    [super viewDidUnload];

}

@end

多点触摸识别

   有些时候,我们只想简单地去识别用户在屏幕上的操作,而不是只针对某个特定的view,我们可以通过以下四个方法进行屏幕的触摸的识别。

touchesBegan:withEvent:当有一个或多个手指触摸屏幕时被触发。

touchesMoved:withEvent:当有一个或多个手指在屏幕上移动时被触发。

touchesEnded:withEvent:当有一个或多个手指离开屏幕时被触发。

touchesCancelled:withEvent: 当系统事件(内存溢出警告或者来电)发生时,取消触摸操作。

检测单点触摸

HomeViewController.h code:

#import <UIKit/UIKit.h>

@interface HomeViewController : UIViewController

@property (retain, nonatomic) IBOutlet UIImageView *imageView;

@end

HomeViewController.m code:

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

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

    NSSet *allTouches = [event allTouches];

    switch ([allTouches count]) {

        case 1:

        {

            UITouch *touch = [[allTouches allObjects] objectAtIndex:0];

            if ([touch tapCount] == 1 ) {

                imageView.contentMode = UIViewContentModeScaleAspectFit;

            }else if ([touch tapCount] == 2) {

                imageView.contentMode = UIViewContentModeScaleAspectFill;

            }

        }

            break;

        default:

            break;

    }

}

- (void)viewDidLoad

{

    [super viewDidLoad];

}

- (void)dealloc {

[imageView release];

    [super dealloc];

}

@end

检测多点触摸

HomeViewController.h code:

#import <UIKit/UIKit.h>

@interface HomeViewController : UIViewController

@property (retain, nonatomic) IBOutlet UIImageView *imageView;

- (CGFloat)distance:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;

@end

HomeViewController.m code: 

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize imageView;

CGFloat originalDistance;

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

    NSSet *allTouches = [event allTouches];

    switch ([allTouches count]) {

        case 1:{

            UITouch *touch = [[allTouches allObjects] objectAtIndex:0];

            if ([touch tapCount] == 1 ) {

                imageView.contentMode = UIViewContentModeScaleAspectFit;

            }else if ([touch tapCount] == 2) {

                imageView.contentMode = UIViewContentModeScaleAspectFill;

            }

        }

            break;

        case 2:{

            UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];

            UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];

            CGPoint touch1PT = [touch1 locationInView:[self view]];

            CGPoint touch2PT = [touch2 locationInView:[self view]];

            NSLog(@"Touch1:%.0f, %.0f", touch1PT.x, touch1PT.y);

            NSLog(@"Touch2:%.0f, %.0f", touch2PT.x, touch2PT.y);

            originalDistance = [self distance:touch1PT toPoint:touch2PT];

        }break;

        default:

            break;

    }

}

- (CGFloat)distance:(CGPoint)fromPoint toPoint:(CGPoint)toPoint{

    float lengthX = fromPoint.x - toPoint.x;

    float lengthY = fromPoint.y - toPoint.y;

    return sqrt((lengthX * lengthX) + (lengthY * lengthY));

}

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

    NSSet *allTouches = [event allTouches];

    switch ([allTouches count]) {

        case 1:

            break;

    case 2:{

        UITouch *touch1 = [[allTouches allObjects] objectAtIndex:0];

        UITouch *touch2 = [[allTouches allObjects] objectAtIndex:1];

        CGPoint touch1PT = [touch1 locationInView:[self view]];

        CGPoint touch2PT = [touch2 locationInView:[self view]];

        NSLog(@"Touch1:%.0f, %.0f", touch1PT.x, touch1PT.y);

        NSLog(@"Touch2:%.0f, %.0f", touch2PT.x, touch2PT.y);

        CGFloat currentDistance = [self distance:touch1PT toPoint:touch2PT];

        if (currentDistance > originalDistance) {

            imageView.frame = CGRectMake(imageView.frame.origin.x-2,imageView.frame.origin.y-2,

                                         imageView.frame.size.width+4, imageView.frame.size.height+4);

        }else {

            imageView.frame = CGRectMake(imageView.frame.origin.x+2, imageView.frame.origin.y+2,

                                         imageView.frame.size.width-4, imageView.frame.size.height-4);

        }

        originalDistance = currentDistance;

    }break;

        default:

            break;

    }

}

- (void)viewDidLoad

{

    [super viewDidLoad];

}

- (void)dealloc {

    [imageView release];

    [super dealloc];

}

@end

你可能感兴趣的:(iPhone开发之手势识别)