常用手势: 滑动,轻点,捏合,旋转,拖拽,长按
1.滑动(快速滑动)
let swipeUp = UISwipeGestureRecognizer(target: self, action: Selector("swipe:")) swipeUp.direction = UISwipeGestureRecognizerDirection.Up self.view.addGestureRecognizer(swipeUp) let swipeDown = UISwipeGestureRecognizer(target: self, action: Selector("swipe:")) swipeDown.direction = UISwipeGestureRecognizerDirection.Down self.view.addGestureRecognizer(swipeDown) let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipe:")) swipeLeft.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(swipeLeft) let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("swipe:")) swipeRight.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRight)
获取手势事件
func swipe(recognizer:UISwipeGestureRecognizer){ if recognizer.direction == UISwipeGestureRecognizerDirection.Up{ print("向左滑动") }else if recognizer.direction == UISwipeGestureRecognizerDirection.Left{ print("向左滑动") } let point = recognizer.locationInView(self.view) print(point.x,point.y) }
2.轻点手势(点击)
//单击监听 let tapSingle = UITapGestureRecognizer(target: self, action: Selector("tapSingleDid")) tapSingle.numberOfTapsRequired = 1//点按的次数 tapSingle.numberOfTouchesRequired = 1//点按的手指数 //双击监听 let tapDouble = UITapGestureRecognizer(target: self, action: Selector("tapDoubleDid:")) tapDouble.numberOfTapsRequired = 2 tapDouble.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(tapSingle) self.view.addGestureRecognizer(tapDouble) //先检测是否为双击,当确定不是双击之后再执行单击 tapSingle.requireGestureRecognizerToFail(tapDouble)
点击事件
func tapSingleDid(){ print("单击") } func tapDoubleDid(sender: UITapGestureRecognizer){ if sender.view == self.view{ print("双击") } }
3.捏合手势
let pinch = UIPinchGestureRecognizer(target: self, action: Selector("pinchDid:")) self.view.addGestureRecognizer(pinch)
事件
func pinchDid(pinch:UIPinchGestureRecognizer){ print(pinch.scale)//捏合比例 }
4.旋转手势
let rotation = UIRotationGestureRecognizer(target: self, action: Selector("rotationDid:")) self.view.addGestureRecognizer(rotation)
事件
func rotationDid(recognizer:UIRotationGestureRecognizer){ print(recognizer.rotation*(180/CGFloat(M_PI)))//转成常用度数了 }
5.拖动手势
var panV : UIView! panV = UIView(frame: CGRectMake(0, 0, 100, 100)) panV.center = self.view.center panV.backgroundColor = UIColor.redColor() self.view.addSubview(panV) let pan = UIPanGestureRecognizer(target: self, action: Selector("panDid:")) panV.addGestureRecognizer(pan)
事件
func panDid(recognizer:UIPanGestureRecognizer){ let point = recognizer.locationInView(self.view) panV.center = point }
6.长按手势
let long = UILongPressGestureRecognizer(target: self, action: Selector("longDid:")) self.view.addGestureRecognizer(long)
事件
func longDid(recognizer:UILongPressGestureRecognizer){ if recognizer.state == .Began{//由于长按会执行多次,所以需要判断手势状态 print("长按手势触发") } }