美文网首页
UIGesture事件

UIGesture事件

作者: 飞飞超人 | 来源:发表于2019-03-26 11:51 被阅读0次

    UIGesture是一种和UITouch方式添加事件不同的体系。手势分为discrete和continuous,即离散和连续,离散手势在判断手势结束时响应一次,连续型会持续响应,但即使对离散型手势也可以判断手势状态,一般只判断end状态。

    可以为任意的UIView通过的addGestureRecognizer方法添加一个或者多个手势(addGestureRecognizeer是在UIView的扩展(UIViewGestureRecognizer)中定义)。

        UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnGestures:)];
        [_titleImageView addGestureRecognizer:gesture];
        
        -(void)OnGestures:(id)sender
        {
            //to do
        }
    

    几种常用的gesture

    TapGestures:

    离散型手势,主要用来响应单击,双击,三击等事件。

    Long-Press Gestures:

    连续型手势,长按手势,可以响应多击长按,但是响应长按手势是靠点击等时间来触发。

    PanGestures:

    连续型手势,我们要跟踪某个手指移动拖动物品之类的都使用它。有一个Edgepangesture,只响应edge的pangesture事件。

    SwipeGestures:

    离散型手势,居然是离散型,可以识别横向和竖向的swipe操作。

    PinchGestures:

    根据两个手指的距离来返回一个缩放因子,初始化1,这个因子是针对初始的大小来计算的,所以不能够一直累加缩放,缩放一定是针对最开始的初始数值。

    RotationGestures:

    根据两个手指连线角度的变化返回一个旋转值,初始化0,这个旋转值是针对初始的大小来计算的,所以不能够一直累加旋转,旋转一定是针对最开始的初始数值。

    下面以pangesture举例子,连续手势的例子:

    var initialCenter = CGPoint()  // The initial center point of the view.
    @IBAction func panPiece(_ gestureRecognizer : UIPanGestureRecognizer) {   
       guard gestureRecognizer.view != nil else {return}
       let piece = gestureRecognizer.view!
       // Get the changes in the X and Y directions relative to
       // the superview's coordinate space.
       let translation = gestureRecognizer.translation(in: piece.superview)
       if gestureRecognizer.state == .began {
          // Save the view's original position. 
          self.initialCenter = piece.center
       }
          // Update the position for the .began, .changed, and .ended states
       if gestureRecognizer.state != .cancelled {
          // Add the X and Y translation to the view's original position.
          let newCenter = CGPoint(x: initialCenter.x + translation.x, y: initialCenter.y + translation.y)
          piece.center = newCenter
       }
       else {
          // On cancellation, return the piece to its original location.
          piece.center = initialCenter
       }
    }
    
    

    多手势响应:

    当添加多个手势的时候,可以在UIGestureRecognizer的delegate中定义是否同时响应UIGestureRecognizer的多种手势,这儿的同时响应是指UIGestureRecognizer内部的,不包括和UIControl类型的事件的同时响应,比如同时响应UIGestureRecognizer定义的tapGesture和panGesture。

    写在最后:

    注意:在IOS中添加事件响应主要有两种种方式,UIGestureRecognizer和UIControl。

    当两种种响应事件同时存在的时候,UIControl的响应优先级高于UIGestureRecognizer。

    相关文章

      网友评论

          本文标题:UIGesture事件

          本文链接:https://www.haomeiwen.com/subject/blkgvqtx.html