IOS学习之手势检测

1、概述:

      UISwipeGestuRecognizer:     滑动(快速滑动)

      UITapGestureRecognizer:      点击(轻点)

      UIPinchGestureRecognizer:    捏合

       UIRotationGestureRecognizer:    旋转

      UIPanGestureRecognizer:       拖动(移动速率较慢)

      UILogPressGestureRecognizer:      长按 

2、工具

      Xcode:7.2,语言:Swift

3、滑动 (UISwipeGestureRecognizer)

    
        let swipe = UISwipeGestureRecognizer(target: self, action: "Swipe");
        /// 定义滑动方向
        swipe.direction = UISwipeGestureRecognizerDirection.Down;
        
        self.view.addGestureRecognizer(swipe);
        这里的代码很简单。初始化时,设置了target 和  action。 同时, 调用View的addGestureRecognizer方法,表示添加一个手势检测。action的方法如下:

    func Swipe()
    {
        print("swipe");
    }
4、  轻点、捏合、旋转

        /*  轻点 */
        let tapSingle = UITapGestureRecognizer(target: self, action: "tapSingle");
        
        /// 设置触摸点数
        tapSingle.numberOfTapsRequired = 1;
        /// 设置点击次数
        tapSingle.numberOfTouchesRequired = 1;
        let tapDouble = UITapGestureRecognizer(target: self, action: "tapDouble");
        tapDouble.numberOfTapsRequired = 2;
        tapDouble.numberOfTouchesRequired = 1;
        
        /// 双击事件不触发单击事件
        tapSingle.requireGestureRecognizerToFail(tapDouble);
        
        /// 添加
        view.addGestureRecognizer(tapDouble);
        view.addGestureRecognizer(tapSingle);
        
        
        /*  捏合  */
        let pinch = UIPinchGestureRecognizer(target: self, action: "pinchTouch:");
        view.addGestureRecognizer(pinch);
        
        /*  旋转手势  */
        let retation = UIRotationGestureRecognizer(target: self, action: "retation:");
        view.addGestureRecognizer(retation);

       下面是action代码:

    func retation(recognizer:UIRotationGestureRecognizer)
    {
        print(recognizer.rotation * (180 / CGFloat(M_PI)));
    }
    
    func pinchTouch(recognizer: UIPinchGestureRecognizer)
    {
        print(recognizer.scale);
    }
    
    func tapDouble()
    {
        print("Double");
    }
    
    func tapSingle()
    {
        print("single");
    }
5、拖动

/*  拖动手势  */
        rect = UIView(frame:CGRectMake(0, 0, 100, 100));
        rect.center = view.center;
        rect.backgroundColor = UIColor.greenColor();
        view.addSubview(rect);
        
        let pan = UIPanGestureRecognizer(target: self, action: "panDid:");
        pan.maximumNumberOfTouches = 1;
        rect.addGestureRecognizer(pan);
  action代码:

func panDid(recognizer:UIPanGestureRecognizer)
    {
        let point = recognizer.locationInView(self.view);
        rect.center = point;
    }
    运行结果(可以拖动有色块移动) :

IOS学习之手势检测_第1张图片

你可能感兴趣的:(swift,手势检测)