-1

I want to detect 3 actions, "Tap begin", "Long press begin", "Long press ended". I want to detect "Tap begin" regardless of detection long tap (i.e. every time when touch the screen, detect "Tap begin") and detect "Tap begin" followed by "long press begin" in case keep touching.

Below code enables to detect "Tap begin" only in case "Long tap" is not detected.

    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.Long(_:)))
    longPressGesture.minimumPressDuration = 3  
    longPressGesture.allowableMovement = 30    

    let shortPressGesture = UITapGestureRecognizer(target: self, action: #selector(self.Tap(_:)))

    touchView.addGestureRecognizer(shortPressGesture)
    touchView.addGestureRecognizer(longPressGesture)

}

@objc func Long(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
    print("Long tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
    print("Long tap ended")
    }
}

@objc func Tap(_ sender: UITapGestureRecognizer) {
    print("Tap begin")
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Zako
  • 61
  • 3

1 Answers1

2

You need to conform to UIGestureRecognizerDelegate

class ViewController: UIViewController, UIGestureRecognizerDelegate

and then implement the shouldRecognizeSimultaneouslyWith function to allow your two gesture recognisers to work at the same time.

Also I think you're actually wanting to use two UILongPressGesutureRecognizers as taps are detected on touch up.

  @objc func Long(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
      print("Long tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
      print("Long tap ended")
    }
  }

  @objc func Tap(_ sender: UILongPressGestureRecognizer) {
    if(sender.state == UIGestureRecognizer.State.began) {
      print("Tap begin")
    } else if (sender.state == UIGestureRecognizer.State.ended) {
      print("Tap ended")
    }
  }

  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if gestureRecognizer == longPressGesture && otherGestureRecognizer == shortPressGesture {
      return true
    }
    return false
  }

Finally don't forget to set the delegates of the gesture recognisers to self

tapPressGesture.delegate = self
shortPressGesture.delegate = self
Cameron Porter
  • 801
  • 6
  • 15