I have created a simple Swift application to test out the UILongPressGestureRecognizer. The app shows the world map (MKMapView) onto the screen where the user can long press on the map and I simply print out the number of times the user has long pressed on the map.
The problem is that when I long press on the map back-to-back, only every alternate long press is detected! So if I were to print out a counter variable which increases every time a long press is detected, I would expect the following:
- I long press on map
- Displays "Tapped 1 times"
- I wait a couple of seconds and then long press on the map again
- Displays "Tapped 2 times"
- I wait a couple of seconds and then long press on the map again
- Displays "Tapped 3 times"
Instead of the above correct functionality, I am getting the below:
- I long press on map
- Displays "Tapped 1 times"
- I wait a couple of seconds and then long press on map again
- Nothing happens!!!!
- I wait a couple of seconds and then long press on map again
- Displays "Tapped 2 times"
Here is my simple code:
// Global variable
var taps:Int = 0
@IBAction func longPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
// Increment counter and print to output
taps += 1
print("Tapped \(taps) times")
}
}
The above code is quite simple so I am not sure what is wrong?
Another interesting note is that if I add the below code after the print("Tapped \(taps) times")
which calculates the position where the user long pressed and moves to that location via the mapView.setRegion() method, I get the correct functionality!!
let touchPositionOnScreen = sender.location(in: mapView)
let convertedLatitude = mapView.convert(touchPositionOnScreen, toCoordinateFrom: mapView!).latitude
let convertedLongitude = mapView.convert(touchPositionOnScreen, toCoordinateFrom: mapView!).longitude
let locationCenter = CLLocationCoordinate2DMake(convertedLatitude, convertedLongitude)
let currentSpan = mapView.region.span
let moveToRegion = MKCoordinateRegion(center: locationCenter, span: currentSpan)
mapView.setRegion(moveToRegion, animated: true)
Has anyone else observed this behavior? Please help.