我想在自定义引脚上显示动态标签。 我使用了MKMapView,CLLocationManager,MKAnnotationView和MKPinAnnotationView。 所以,请帮助我的朋友。
像:
答案 0 :(得分:1)
首先创建一个基于自定义MKAnnotationView
的类:
Swift 3
class CustomAnnotationView: MKAnnotationView {
var label: UILabel?
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
然后确保您的ViewController类添加NKMapViewDelegate
作为委托:
Swift 3
import UIKit
import MapKit
class ViewController: MKMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
}
然后将以下方法添加到ViewController
,每当注释添加到地图时,MapView将调用该方法:
Swift 3
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationIdentifier = "MyCustomAnnotation"
guard !annotation.isKind(of: MKUserLocation.self) else {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
if annotationView == nil {
annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
if case let annotationView as CustomAnnotationView = annotationView {
annotationView.isEnabled = true
annotationView.canShowCallout = false
annotationView.label = UILabel(frame: CGRect(x: -5.5, y: 11.0, width: 22.0, height: 16.5))
if let label = annotationView.label {
label.font = UIFont(name: "HelveticaNeue", size: 16.0)
label.textAlignment = .center
label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.adjustsFontSizeToFitWidth = true
annotationView.addSubview(label)
}
}
}
if case let annotationView as CustomAnnotationView = annotationView {
annotationView.annotation = annotation
annotationView.image = #imageLiteral(resourceName: "YourPinImage")
if let title = annotation.title,
let label = annotationView.label {
label.text = title
}
}
return annotationView
}
完成所有这些后,可以像这样添加注释:
Swift 3
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: /* latitude */, longitude: /* longitude */)
annotation.title = "Your Pin Title"
mapView.addAnnotation(annotation)
答案 1 :(得分:0)
如果您的意思是您希望图钉上有一个字母,那么您需要在viewForAnnotation
中设置注释视图的图像。如果您计划更改每个注释的引脚,则需要动态创建图像。他们将围绕这个充足的代码,但它归结为这个
annotationView.image = anImage;