0

If I add a new custom annotation, and click the button to pop up the callout, OR click anywhere on the map, nothing happens. If I click again, everything works... Any ideas? I have looked at many theories, but so far no luck...

@IBOutlet weak var mapView: MKMapView!

// In ViewDidLoad, I define my LongPressGestureRecognizer
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(createNewAnnotation))
uilpgr.minimumPressDuration = 0.25
mapView.addGestureRecognizer(uilpgr)

// And here is the selector:
@objc func createNewAnnotation(_ sender: UIGestureRecognizer) {

let touchPoint = sender.location(in: self.mapView)
let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)

let heldPoint = MKPointAnnotation()
heldPoint.coordinate = coordinates

if (sender.state == .began) {
    heldPoint.title = "Set Point"
    heldPoint.subtitle = String(format: "%.4f", coordinates.latitude) + "," + String(format: "%.4f", coordinates.longitude)
    mapView.addAnnotation(heldPoint)

 }        
}

If I replace the long press by a tap recognizer, the callout shows up, but the tap creates yet another annotation...so long press has to be the right way. But how can I get around this problem, so that the user can create the annotation with a long press, and then tap once to get the callout??

TylerH
  • 20,799
  • 66
  • 75
  • 101
marhab
  • 29
  • 3
  • I now have figured out what is going on: because my annotation is created inside of a LongPressGesture handler, it nullifies the next tap for some reason. I have reproduced this in sample code, and it seems to always happen as long as there is a long press gesture. Any ideas? – marhab May 08 '20 at 22:57

1 Answers1

1

So, I finally found the solution after looking for about 3 whole days...What happens is that the Long Press continues to obscure all other gestures. So the next tap is not recognized, only the second tap. The fix is incredibly simple, fixed in the selector as such:

    @objc func createNewAnnotation(_ sender: UIGestureRecognizer) {

    let touchPoint = sender.location(in: self.mapView)
    let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)

    let heldPoint = MKPointAnnotation()
    heldPoint.coordinate = coordinates

    if (sender.state == .began) {
        heldPoint.title = "Set Point"
        heldPoint.subtitle = String(format: "%.4f", coordinates.latitude) + "," + String(format: "%.4f", coordinates.longitude)
        mapView.addAnnotation(heldPoint)
 } 
    // Cancel the long press gesture!
    sender.state = .cancelled      
}

With this miniature change, the LongPress goes away, and the tap gets handled by the map and the annotation.

marhab
  • 29
  • 3