我在mapkit中有2个图钉,它们都在同一个注释视图下,所以由于两个图钉都具有相同的颜色,所以它可以进行绘制。如何使别针颜色不同。我想你好是红色,你好是蓝色。
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var jmap: MKMapView!
override func viewDidLoad() {
jmap.delegate = self;
let hello = MKPointAnnotation()
hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73)
jmap.addAnnotation(hello)
let hellox = MKPointAnnotation()
hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72)
jmap.addAnnotation(hellox)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView()
annotationView.pinTintColor = .blue
return annotationView
}}
最佳答案
子类MKPointAnnotation
以添加所需的任何自定义属性,例如pinTintColor
:
class MyPointAnnotation : MKPointAnnotation {
var pinTintColor: UIColor?
}
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var jmap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
jmap.delegate = self
let hello = MyPointAnnotation()
hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73)
hello.pinTintColor = .red
let hellox = MyPointAnnotation()
hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72)
hellox.pinTintColor = .blue
jmap.addAnnotation(hello)
jmap.addAnnotation(hellox)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation")
} else {
annotationView?.annotation = annotation
}
if let annotation = annotation as? MyPointAnnotation {
annotationView?.pinTintColor = annotation.pinTintColor
}
return annotationView
}
}