如果需要,MKPointAnnotation的默认实现会在引脚下方显示标题:
我实现了viewFor Annotation以使用自定义图像,这消除了MKPointAnnotation的标题功能。
此代码位于MapViewController的viewDidLoad中的网络代码中,并从位置对象的共享实例数组中提取位置数据,以创建我的CustomAnnotation类的相应实例:
// Create the annotations
var tempArray = [CustomAnnotation]()
for dictionary in Location.sharedInstance {
let lat = CLLocationDegrees(dictionary.latitude)
let long = CLLocationDegrees(dictionary.longitude)
let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
let name = dictionary.name
let annotation = CustomAnnotation(coordinates: coordinates, title: name)
tempArray.append(annotation)
}
// Add the annotations to the annotations array
self.mapView.removeAnnotations(self.annotationArray)
self.annotationArray = tempArray
self.mapView.addAnnotations(self.annotationArray)
}
这是我的CustomAnnotation类:
class CustomAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D()
var title: String?
init(coordinates location: CLLocationCoordinate2D, title: String) {
super.init()
self.coordinate = location
self.title = title
}
}
这是我的观点:实施:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !(annotation is MKUserLocation) else {
return nil
}
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
}
if let annotationView = annotationView {
for location in Location.sharedInstance {
if annotationView.annotation?.coordinate.latitude == location.latitude && annotationView.annotation?.coordinate.longitude == location.longitude {
if location.rating < 2 {
annotationView.image = UIImage(named: "1star")
} else if location.rating == 2 {
annotationView.image = UIImage(named: "2star")
} else if location.rating == 2.5 {
annotationView.image = UIImage(named: "2star")
} else if location.rating == 3.0 {
annotationView.image = UIImage(named: "3star")
} else if location.rating == 3.5 {
annotationView.image = UIImage(named: "3star")
} else if location.rating == 4.0 {
annotationView.image = UIImage(named: "4star")
} else if location.rating == 4.5 {
annotationView.image = UIImage(named: "4star")
} else if location.rating > 4.5 {
annotationView.image = UIImage(named: "5star")
}
}
}
}
return annotationView
}
是否有一种移植MKPointAnnotation标题格式的简单方法,还是我必须制作自定义视图?也许同样重要的是,可以安全地假设我需要编写一些逻辑来防止来自紧密定位的引脚的标题成为混乱的文本? Apple的MKPointAnnotation似乎内置了这种逻辑,因为它只是拒绝显示许多标题。