例: 创建UIImageview,添加手势
//创建imageview
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
imageView.backgroundColor = [UIColor blueColor];
imageView.center = self.view.center;
[self.view addSubview:imageView];
[imageView release];
//开启用户交互
imageView.userInteractionEnabled = YES;
#pragma mark - 1.轻怕
//创建手势对象
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
//手指个数
tap.numberOfTouchesRequired = 2;
//轻拍次数
tap.numberOfTapsRequired = 2;
//把手势添加给视图
[imageView addGestureRecognizer:tap];
[tap release];
#pragma mark - 2.长按 longPress
//创建对象
UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longAction:)];
//最少长按时间
longpress.minimumPressDuration = 2;
//添加
[imageView addGestureRecognizer:longpress];
[longpress release];
#pragma mark - 3.捏合 pinch
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
[imageView addGestureRecognizer:pinch];
[pinch release];
#pragma mark - 4.轻扫
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
//轻扫方向
swipe.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
[imageView addGestureRecognizer:swipe];
[swipe release];
#pragma mark- 手势识别器触发方法
//轻拍
- (void)tapAction:(UITapGestureRecognizer *)tap
{
NSLog(@"轻拍");
}
//长按触发方法
- (void)longAction:(UILongPressGestureRecognizer *)longpress
{
//其他部分手势也会触发长按
//长按约束
if (longpress.state == UIGestureRecognizerStateBegan) {
NSLog(@"长按开始");
}
NSLog(@"长按: %@", longpress);
}
//捏合
- (void)pinch:(UIPinchGestureRecognizer *)pinch
{
NSLog(@"捏合开始");
//捏合时图片跟随变化
//1.获取图片对象
UIImageView *img = (UIImageView *)pinch.view;
//2.等比例缩放
[img setTransform:CGAffineTransformScale(img.transform, pinch.scale, pinch.scale)];
}
//轻扫
- (void)swipeAction:(UISwipeGestureRecognizer *)swipe
{
NSLog(@"轻扫: %@", swipe);
}