Custom Annotation Swift

陌路散爱 提交于 2019-12-25 08:28:56

问题


I have created a map which contains a single annotation. From what I've seen, this is a very simple way of achieving this which I got off a tutorial. I am currently trying to get a custom picture as the annotation but am struggling to do so as almost all information on this topic is in objective C. Forgive me if it is really simple to do but I am relatively new to coding and would appreciate any help :)

class ViewController2: UIViewController {
@IBOutlet var Map: MKMapView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

//Location for first Pin
let locationOne = CLLocationCoordinate2DMake(-47.016945, 167.852095)

//Location for map centering
let locationNZ = CLLocationCoordinate2DMake(-43.937462, 170.507813)
let span = MKCoordinateSpanMake(9, 9)
let region = MKCoordinateRegion(center: locationNZ, span: span)
Map.setRegion(region, animated: true)

//Create annotation one
let annotation = MKPointAnnotation()
annotation.coordinate = locationOne
annotation.subtitle = "Park"
annotation.title = "Rakiura National Park"

//Add annotation to the map
Map.addAnnotation(annotation)}

回答1:


I assume its a different image of the default pin you want? I've used this answer from another question, check it out here Custom pin image in annotationView in iOS

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
guard !annotation.isKindOfClass(MKUserLocation) else {
    return nil
}

let annotationIdentifier = "AnnotationIdentifier"

var annotationView: MKAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) {
    annotationView = dequeuedAnnotationView
    annotationView?.annotation = annotation
}
else {
    let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
    av.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
    annotationView = av
}

if let annotationView = annotationView {
    // Configure your annotation view here
    annotationView.canShowCallout = true
    annotationView.image = UIImage(named: "yourImage")
}

return annotationView
}


来源:https://stackoverflow.com/questions/41480737/custom-annotation-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!