MKPinAnnotationView 是 MapKit 框架中的一个类,用于在地图上显示标准的图钉标记。它是 MKAnnotationView 的子类,专门用于显示带有颜色和动画效果的图钉标记。
MKPinAnnotationView 未显示标题通常有以下几种原因:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let identifier = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
pinView?.canShowCallout = true // 关键设置
pinView?.animatesDrop = true
} else {
pinView?.annotation = annotation
}
return pinView
}
class MyAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
// 使用时
let annotation = MyAnnotation(coordinate: location, title: "我的位置", subtitle: "详细信息")
mapView.addAnnotation(annotation)
确保没有其他视图遮挡了标注视图,可以通过以下方式调试:
mapView.bringSubviewToFront(pinView)
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let location = CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074)
let annotation = MyAnnotation(coordinate: location, title: "北京", subtitle: "中国首都")
mapView.addAnnotation(annotation)
let region = MKCoordinateRegion(center: location, latitudinalMeters: 10000, longitudinalMeters: 10000)
mapView.setRegion(region, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else { return nil }
let identifier = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
pinView?.canShowCallout = true
pinView?.animatesDrop = true
} else {
pinView?.annotation = annotation
}
return pinView
}
}
class MyAnnotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
通过以上步骤,应该能够解决 MKPinAnnotationView 标题未显示的问题。