如何在Mapview swift ios中设置自定义图钉图像?
问题描述:
@IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
map.delegate = self
showAlarms()
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func showAlarms(){
map.region.center.latitude = 10.733051
map.region.center.longitude = 76.763042
map.region.span.latitudeDelta = 1
map.region.span.longitudeDelta = 1
}
func mapView(mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
//pinView!.animatesDrop = true
pinView!.image = UIImage(named:"annotation")!
}
else {
pinView!.annotation = annotation
}
return pinView
}
我需要在swift ios中显示我的mapview的自定义图钉图像。自定义图像不会加载该引脚。我有一个名为“注释”的图像,我需要在我的mapview中加载。如何在Mapview swift ios中设置自定义图钉图像?
答
mapview.delegate = self
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
let annotationIdentifier = "Identifier"
var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
if let annotationView = annotationView {
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "yourImagename”)
}
return annotationView
}
答
您还可以创建自定义MKAnnotationView并设置在图像内:
class myCustomAnnotationView : MKAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let annotation = newValue else {return}
switch annotation {
case is myCustomMKAnnotation:
self.canShowCallout = true
self.image = #yourimage
self.centerOffset = CGPoint(x: 0, y: -self.image!.size.height/2)
break
default:
return
}
self.setAnimationLayer()
}
}
然后所有你需要做的是:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { return nil }
guard !(annotation is MKUserLocation) else {
let annotationIdentifier = "Identifier"
if let myAnnotation = annotation as? myCustomMKAnnotation {
let annotation = myCustomAnnotationView(annotation: siteAnnotation, reuseIdentifier: annotationIdentifier)
return annotation
}
return nil
}
我认为它看起来更清洁一样,
viewForAnnotation的委托方法是否为您调用。 –
@KiritModi。我不这么认为。它只显示地图,没有别的。请帮忙。 – Rakesh
你是swift 3中的代码 –