Reputation: 53
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...
Upvotes: 0
Views: 1194
Reputation: 3025
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))")
}
}
Upvotes: 1
Reputation: 318794
You need to move locationOfBeganTap
to be an instance variable instead of a local variable.
class WhatEverClassThisIs {
var locationOfBeganTap: CGPoint?
// and the rest of your stuff
func handleTestViewTap (panRecognizer: UIPanGestureRecognizer){
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)")
}
}
}
Upvotes: 0