swift - 为什么我的注释标注不会出现?标注仅在使用自定义图像作为图钉时有效
问题描述
出于某种原因,我的 MapView 上的注释只会在使用自定义图像作为注释时显示标注。但是,我喜欢通用注释的简洁外观,并且不想使用自定义图像。我的代码有什么问题?
一般来说,我对编程相当陌生,并尝试在不同的网站上提问,但找不到答案。
@IBAction func onMoreTapped() {
print("TOGGLE SIDE MENU")
NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil)
}
@IBAction func mapSwitch(_ sender: UISwitch) {
if (sender.isOn == true) {
mapView.mapType = MKMapType.standard
}
else {
mapView.mapType = MKMapType.hybrid
}
}
var tappedAnnotation : MKAnnotation?
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKPinAnnotationView? {
if let view = mapView.dequeueReusableAnnotationView(withIdentifier: "Annotation") {
view.annotation = annotation
return view as! MKPinAnnotationView
} else {
let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Annotation")
view.isEnabled = true
view.canShowCallout = true
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
return view
}
}
func mapView(_ mapView: MKMapView, annotationView view: MKPinAnnotationView, calloutAccessoryControlTapped control: UIControl) {
tappedAnnotation = view.annotation
performSegue(withIdentifier: "showAnnotationDetails", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAnnotationDetails", let dest = segue.destination as? AnnotationDetails {
dest.annotation = tappedAnnotation
}
}
func createAnnotations ( _ annotations : [String:[String:Any]] ) {
mapView.removeAnnotations(mapView.annotations)
for (_,values) in annotations {
if let latDouble = values["latitude"] as? Double, let longDouble = values["longitude"] as? Double {
let lat = CLLocationDegrees( latDouble )
let long = CLLocationDegrees( longDouble )
let coord = CLLocationCoordinate2D(latitude: lat, longitude: long)
let annotation = MKPointAnnotation()
annotation.coordinate = coord
annotation.title = values["name"] as? String ?? ""
annotation.subtitle = values["info"] as? String ?? ""
mapView.addAnnotation(annotation)
courtAmountLabel.title = "\(mapView.annotations.count-1) Courts"
}
}
}
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
courtAmountLabel.tintColor = UIColor.black
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
mapView.delegate = self
//
mapView.showsUserLocation = true
mapView.mapType = MKMapType.standard
let ref = Database.database().reference()
ref.child("annotations").observe(.value) { snapshot in
print(snapshot)
if let annotations = snapshot.value as? [String:[String:Any]] {
self.createAnnotations(annotations)
} else {
print("Data received not formatted as expected")
}
}
我希望出现注释标注,这将允许应用程序用户按下并访问另一个页面。
解决方案
利用
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
代替
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKPinAnnotationView? {