出现MKMapView上的PointAnnotation标注,然后立即消失

时间:2015-08-21 10:23:37

标签: ios swift annotations mkmapview callout

我正在UITapGestureRecognizer委托中使用标注创建一个简单的点注释。

我第一次点击地图时,针脚出现了标注,但标注后会立即消失。

第二次点击相同的引脚时,标注出现并停留在那里,不知道为什么它会在第一时间消失。

@IBAction func handleMapTouch(recognizer: UITapGestureRecognizer){
    let view = recognizer.view
    let touchPoint=recognizer.locationInView(view)
    var touchCord=CLLocationCoordinate2D()

    touchCord = mapView.convertPoint(touchPoint, toCoordinateFromView:
     mapView)

        mapView.removeAnnotations(mapView.annotations)
        pointAnnotation.coordinate=touchCord
        pointAnnotation.title="ABC"
        pointAnnotation.subtitle="DEF"

        mapView.addAnnotation(pointAnnotation)
        mapView.selectAnnotation(pointAnnotation, animated: true)


}

2 个答案:

答案 0 :(得分:1)

我有同样的问题。我也不知道如何解决它,但我找到了解决方法。也许它也可以帮到你。

我使用LongPressGesture替换TapGesture

在Viewdidload中:

let longPress = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
longPress.minimumPressDuration = 0.1
self.mapView.addGestureRecognizer(longPress)

在函数addAnnotation中:

if(gestureRecognizer.state == .Ended){
    self.mapView.removeGestureRecognizer(gestureRecognizer)

    //remove all annotation on the map
    self.mapView.removeAnnotations(self.mapView.annotations)

    //convert point user tapped to coorinate
    let touchPoint: CGPoint! = gestureRecognizer.locationInView(self.mapView)
    let touchMapCoordinate: CLLocationCoordinate2D = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
    showCustomAnnotation(touchMapCoordinate)
}
self.mapView.addGestureRecognizer(gestureRecognizer)

答案 1 :(得分:1)

以防其他人遇到同样的问题,虽然Keith的回答有效,但就我而言,它会破坏与地图相关的其他手势,例如捏合和缩放。

对我来说,延迟几毫秒显示标注的操作效果更好。

在Swift 3中:

let deadlineTime = DispatchTime.now() + .milliseconds(500)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  mapView.addAnnotation(pointAnnotation)
  mapView.selectAnnotation(pointAnnotation, animated: true)
}