ios手势操作

#import "ViewController.h"

#define WIDTH (NSUInteger)self.view.bounds.size.width
#define HEIGHT (NSUInteger)self.view.bounds.size.height

@interface ViewController ()
{
    UIImageView *imageView;
}

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建一个imageView对象
    UIImage *image = [UIImage imageNamed:@"meinv.jpg"];
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    imageView.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    imageView.image = image;
    // 设置UIImageView对象具有交互能力(这句话很重要)
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    
    [self creatGestureRecognizer];
}

创建手势识别器

- (void) creatGestureRecognizer{
    
    // 创建点击手势
    UITapGestureRecognizer *r0 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doTap:)];
    // 设置点击次数
    r0.numberOfTapsRequired = 2;
    [imageView addGestureRecognizer:r0];
    
    // 创建滑动手势识别器 每一个只能识别一种方向 所以一般需要创建4个
    for (int i=0; i<4; i++) {
        UISwipeGestureRecognizer *r1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSwipe:)];
        // 设置手势识别器的方向(枚举值)
        r1.direction = 1 << i ;
        [imageView addGestureRecognizer:r1];
    }
    
    // 创建旋转手势识别器
    UIRotationGestureRecognizer *r2 = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(doRotate:)];
    r2.delegate = self;
    [imageView addGestureRecognizer:r2];
    
    // 创建捏合手势识别器
    UIPinchGestureRecognizer *r3 = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(doPinch:)];
    r3.delegate = self;
    [imageView addGestureRecognizer:r3];
    
    // 创建长按手势
    UILongPressGestureRecognizer *r4 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doLongPress:)];
    // 设置长按时间 默认0.5s
    r4.minimumPressDuration = 0.5;
    [imageView addGestureRecognizer:r4];
}
- (void) doTap:(UITapGestureRecognizer *)sender{
    NSLog(@"点击已生效");
}
- (void) doSwipe:(UISwipeGestureRecognizer *) sender{
    // 这里可以选判断滑动方向
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"右滑已生效");
    }
}
-(void) doRotate:(UIRotationGestureRecognizer *) sender{
    // 通过仿射变换旋转UIImageView
    imageView.transform = CGAffineTransformRotate(imageView.transform, sender.rotation);
    // 防止旋转效果叠加
    sender.rotation = 0;
}
-(void) doPinch:(UIPinchGestureRecognizer *) sender{
    imageView.transform = CGAffineTransformScale(imageView.transform, sender.scale, sender.scale);
    // 每次放大缩小之后置1
    sender.scale = 1;
}
- (void) doLongPress:(UILongPressGestureRecognizer *) sender{
    // 需要判断一下 防止长按之后移动会一直打印
    if (sender.state == UIGestureRecognizerStateBegan) {
        NSLog(@"长按已生效");
    }
}
// 返回YES 同时支持多个手势操作的回调方法 需要绑定委托
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

你可能感兴趣的:(ios手势操作)