如何防止取消选择注释自动快速

时间:2017-12-30 11:31:48

标签: ios swift mapkit mkmapviewdelegate

我有一张里面有地图的视图。我想实现以下目标:当用户点击地图时,会显示并选择注释(因此会显示标注气泡),直到用户点击地图上的另一个点(在这种情况下,应删除之前的注释) )。

问题在于,当我点击地图时,注释会被添加并选择一段时间,然后以某种方式取消选择(因此标注消失)。我希望标注气泡持续到用户点击另一个点

以下是我的尝试,有人可以帮助我吗?

@objc func handleTap(_ sender: UITapGestureRecognizer){

    //...some code that computes the country code starting from latitude and longitude

            var countryCurrency = ""

            func countryRequest(countryLabel: String, completion: @escaping (String)->()){
                //api request that receives the currency name of the country
                completion(countryCurrency)
            }
            countryRequest(countryLabel: countryLabel){ countryCurrency in

                DispatchQueue.main.async {

                    let locat:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationCoord.latitude, locationCoord.longitude)
                    let annotation = MKPointAnnotation()
                    annotation.coordinate = locat
                    annotation.title = countryCurrency
                    annotation.subtitle = "subtitle"
                    self.mapView.addAnnotation(annotation)
                    self.mapView.selectAnnotation(annotation, animated: true)

                }

            }
}

我还有MKMapViewDelegate的扩展来自定义标注:

extension MapsItem: MKMapViewDelegate {

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if !(annotation is MKPointAnnotation){
        return nil
    }

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "demo")
    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "demo")
        annotationView!.canShowCallout = true
        annotationView!.sizeToFit()
    }
    else{
        annotationView!.annotation = annotation
    }

    return annotationView

}
}

提前致谢!!

2 个答案:

答案 0 :(得分:2)

试试这个

在添加注释之前将isTappingNow设置为true,并在选择之后将其设置为false

   func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView)
   {

      if(!isTappingNow)
      {

           self.mapView.selectAnnotation(view.annotation, animated: false)
      } 

    }

答案 1 :(得分:0)

一直在寻找解决办法,不知道为什么会这样,是不是bug?现在,我做了一个技巧来延迟它的出现。 @Sh_Khan 的解决方案会再闪一次标注,我的解决方案会让用户不得不等待一段时间

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

    let locat:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationCoord.latitude, locationCoord.longitude)
    let annotation = MKPointAnnotation()
    annotation.coordinate = locat
    annotation.title = countryCurrency
    annotation.subtitle = "subtitle"
    self.mapView.addAnnotation(annotation)
    self.mapView.selectAnnotation(annotation, animated: true)
}