swift -> 给随便控件添加 手势(点击,拖拽等) 事件

swift -> 给任意控件添加 手势(点击,拖拽等) 事件

   

   1、拍击UITapGestureRecognizer (任意次数的拍击)  
    2、向里或向外捏UIPinchGestureRecognizer (用于缩放)  
    3、摇动或者拖拽UIPanGestureRecognizer  
    4、擦碰UISwipeGestureRecognizer (一般用以左右切换滑动)  
    5、旋转UIRotationGestureRecognizer (手指朝相反方向移动)  
    6、长按UILongPressGestureRecognizer 

 

 

    override func viewDidLoad() {
        super.viewDidLoad()
 
        var v = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)); 
        
        //点击事件
        let handTap = UITapGestureRecognizer(target: self, action: #selector(funTap))
        v.addGestureRecognizer(handTap)

        //拖动事件, 任意方向
        let handDrag = UIPanGestureRecognizer(target: self, action: #selector(funDrag))
        //v.addGestureRecognizer(handDrag)
        
        //左右滑动,不可与拖动事件UIPanGestureRecognizer并存 , 默认只支持向右
        let handLeftRight = UISwipeGestureRecognizer(target: self, action: #selector(funLeftRight))
        handLeftRight.direction = .left //支持向左
        v.addGestureRecognizer(handLeftRight)
        
        self.view.addSubview(v)

    }

    func funTap(sender: UIPanGestureRecognizer){
        print("funTap_"+String(arc4random()));
    }
    func funDrag(sender: UIPanGestureRecognizer){
        var Point = sender.translation(in: self.view);//现对于起始点的移动位置
        Point = sender.location(in: self.view);//在整个self.view 中的位置
        print("funDrag_"+String(describing: Point.x)+","+String(describing:Point.y))
    }
    func funLeftRight(sender: UIPanGestureRecognizer){
        print("funLeftRight_"+String(arc4random()));
    }