4
votes

I am trying to determine if there is a means of programmatically setting a gesture recognizer state, to force it to begin prior to it actually detecting user input.

For example, I am adding a pan gesture recognizer to an image when a long press is detected, like so;

let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
myImage.addGestureRecognizer(longPressRecognizer)

func longPressed(sender: UILongPressGestureRecognizer) {

   let mainWidth = UIScreen.mainScreen().bounds.width
   let mainHeight = UIScreen.mainScreen().bounds.height

   let myView: UIView(frame: CGRect(x: 0, y: 0, width: mainWidth, height: mainHeight)

   let gestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
   myView.addGestureRecognizer(gestureRecognizer)

   self.view.addSubview(myView)

}

In the handlePan() function, I'm able to determine when the pan starts and ends;

func handlePan(gesture: UIPanGestureRecognizer) {

    if gesture!.state == UIGestureRecognizerState.Began {
        print("Started pan")
    }

    if gesture!.state == UIGestureRecognizerState.Ended {
        print("Ended pan")
    }

}

My issue is that, to detect when the gesture started, the user has to (1) long press on the image, (2) release their finger, (3) press and hold and start panning. Ideally, I'd like to have the user (1) long press on the image, (2) start panning.

To accomplish this, I'm imagining I need to figure out a way to "trick" things into believing that the pan gesture already began.

note: In practicality, there is more complexity than what's presented here, which is why I need to add a subview with the pan gesture, rather than just adding the pan gesture to the image directly.

1
Could you make the touch a "Touch Down" event instead of a "Touch Up Inside". Then you wouldn't need to release your finger for the event to be sent.JoakimE

1 Answers

1
votes

What you want to do is add both gesture recognizes up front, set their delegates to your class, allow them to recognize simultaneously (using the below method), and only use the data from the pan when the long press has successfully been recognized.

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
    shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}