Eco Apps Eco Apps - 2 months ago 7
Swift Question

How to access the initial point of a Pan Gesture in it's .Ended state

I am trying to implement a Pan Gesture in my app where I need to access the initial point in the .Ended state.

Here is the code.

func handleTestViewTap (panRecognizer: UIPanGestureRecognizer){

var locationOfBeganTap: CGPoint?

if panRecognizer.state == UIGestureRecognizerState.Began {
locationOfBeganTap = panRecognizer.locationInView(view)
print("locationOfBeganTap in BEGAN State -> .\(locationOfBeganTap)")

} else if panRecognizer.state == UIGestureRecognizerState.Ended {
print("locationOfBeganTap -> .\(locationOfBeganTap)")
print("locationOfBeganTap in ENDED State -> .\(locationOfBeganTap)")

}
}


Now, here is the output:

locationOfBeganTap in BEGAN State -> .Optional((195.5, 120.0))
locationOfBeganTap in ENDED State -> .nil


I am unable to understand why the
locationOfBeganTap
is
nil
in the
.Ended
state

Can someone please share the code to access
locationOfBeganTap
in
.Ended
state...

J F J F
Answer

The way you are doing this doesn’t work. Instead, calculate it all at the end:

func handleTestViewTap (panRecognizer: UIPanGestureRecognizer){

    if panRecognizer.state == UIGestureRecognizerState.Ended {            
        print("locationOfBeganTap -> (.\(touch.locationInView(view).x - touch.translationInView(view).x), .\(touch.locationInView(view).y - touch.translationInView(view).y))")
        print("location in ENDED State -> .\(touch.locationInView(view))")
    }     
}
Comments