添加viewForAnnotations

所以我是第一次使用MapKit,并且尝试显示带有标注的注释。

出现注释,但是一旦添加委托函数viewFor注释(func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {}),注释就不再显示。该功能中我缺少什么吗?

修改

我忘了提到视图控制器是mkmapviewdelegate的委托

@objc func addAnnotationOnLongPress(gesture: UILongPressGestureRecognizer) {

        if gesture.state == .ended {
            let point = gesture.location(in: self.mapView)
            let coordinate = self.mapView.convert(point,toCoordinateFrom: self.mapView)
            //Now use this coordinate to add annotation on map.
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate

            usf.fetchJSON(urlString: usf.setNewLocation(lat: annotation.coordinate.latitude,lon: annotation.coordinate.longitude)) { (data,success) in
                if success {
                    annotation.title = data?.name
                    annotation.subtitle = "HAa"
                } else {
                    let alertUI = self.usf.createAlertOK(title: "Something went wrong!",message: "Cannot get the current weather! \n Check your connectivity or try again later")
                    self.present(alertUI,animated: true,completion: nil)
                }
            }
            let previousAnnotations = self.mapView.annotations
            if !previousAnnotations.isEmpty{
              self.mapView.removeAnnotation(previousAnnotations[0])
            }
            self.mapView.addAnnotation(annotation)
        }        
    }



    func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
        print("in viewFor annotation") // prints out
        let annotationView = MKAnnotationView(annotation: annotation,reuseIdentifier: "TempAnnotationView")
        annotationView.canShowCallout = true
        annotationView.rightCalloutaccessoryView = UIButton(type: .detailDisclosure)
        self.mapView.showAnnotations(mapView.annotations,animated: false)
        return annotationView
    }

nut0032 回答:添加viewForAnnotations

您需要

if success {
    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    annotation.title = data?.name
    annotation.subtitle = "HAa"
    self.mapView.addAnnotation(annotation)
}

获取名称的api是异步的,因此您必须在回调中添加填充的注释

,

您正在实例化MKAnnotationView。如果您有一些自定义图像,请设置此MKAnnotationView的{​​{3}}属性。或者,更简单地,只需使用imageMKPinAnnotationView即可。

作为Sh_Kahn MKMarkerAnnotationView,请确保您在闭包内部而不是在其后创建注释。

本文链接:https://www.f2er.com/2820117.html

大家都在问