简体   繁体   中英

After adding a new annotation, my first tap is not handled, but the second tap is

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??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM