UIGestureRecognizer抽象类

UIGestureRecognizer抽象类不能直接使用,而是使用它的不同子类。

  • UITapGestureRecognizer: 点击
  • UISwipeGestureRecognizer: 滑动
  • UIPanGestureRecognizer: 滑动
  • UIPinchGestureRecognizer: 缩放
  • UIRotationGestureRecognizer: 转换方向
  • UILongPressGestureRecognizer: 长按操作
  • UIScreenEdgePanGestureRecognizer: 边缘滑动

如何在视图中添加手势操作

步骤一:创建并初始化UIGestureRecognizer的子类

//创建初始化一个UIGestureRecognizer的子类UITapGestureRecognizer,target是self,动作是handleSingleTapGesture:
UITapGestureRecognizer singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
//添加双击手势识别
UITapGestureRecognizer doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTapGesture:)];

//在识别手势前对单击手势暂不识别 [singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer];

doubleTapGestureRecognizer.numberOfTapsRequired = 2; doubleTapGestureRecognizer.delaysTouchesBegan = YES;

根据需要设置UIGestureRecognizer的属性

步骤二:将手势依附到相应的视图上

[self.testView addGestureRecognizer:singleTapGestureRecognizer];
[self.testView addGestureRecognizer:doubleTapGestureRecognizer];

步骤三:实现手势事件

- (void)handleSingleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer
{
    CGFloat newWidth = 100.0;
    if (self.testView.frame.size.width == 100.0) {
        newWidth = 200.0;
    }

CGPoint currentCenter = self.testView.center;

self.testView.frame = CGRectMake(self.testView.frame.origin.x, self.testView.frame.origin.y, newWidth, self.testView.frame.size.height);
self.testView.center = currentCenter;

}

  • (void)handleDoubleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer { CGSize newSize = CGSizeMake(100.0, 100.0); if (self.testView.frame.size.width == 100.0) { newSize.width = 200.0; newSize.height = 200.0; }

    CGPoint currentCenter = self.testView.center;

    self.testView.frame = CGRectMake(self.testView.frame.origin.x, self.testView.frame.origin.y, newSize.width, newSize.height); self.testView.center = currentCenter; }