所以我是第一次使用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
}