Combining a UILongPressGestureRecognizer with a UIPanGestureRecognizer

前端 未结 6 490
醉梦人生
醉梦人生 2020-11-30 08:57

I d\'like to combine a UILongPressGestureRecognizer with a UIPanGestureRecognizer.

The UIPanGestureRecognizer should start with a long press. Is there a simple way

6条回答
  •  眼角桃花
    2020-11-30 09:16

    For combinate more gesture :

    1. Create a local variable var shouldAllowSecondGesture : Bool = false
    2. Create the two recognizer

    let longPressRec = UILongPressGestureRecognizer(target: self, action: #selector(self.startDrag(sender:))) cell.addGestureRecognizer(longPressRec) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(sender:))) cell.isUserInteractionEnabled = true cell.addGestureRecognizer(panGestureRecognizer)

    1. Extension your VC and implement GestureRecognizerDelegate for implemented this method.

      extension YourViewController : UIGestureRecognizerDelegate {

      func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
              return true
          }
      
      
      
      func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
               // We only allow the (drag) gesture to continue if it is within a long press
               if((gestureRecognizer is UIPanGestureRecognizer) && (shouldAllowPan == false)) {
                   return false
               }
               return true
          }
      
      
      @objc func startDrag(sender:UIPanGestureRecognizer) {
      
          if(sender.state == .began) {
                  // handle the long press
              }
          else if(sender.state == .changed){
                  shouldAllowPan = true
      
              }
              else if (sender.state == .ended) {
                  shouldAllowPan = false
              }
          }
      

提交回复
热议问题