无法在MapView,Swift 3中设置自定义图像

时间:2017-08-25 21:54:08

标签: ios swift annotations mapkit mkpinannotationview

迷你地图代码:

import UIKit
import MapKit

@IBOutlet weak var ProfileMapView: MKMapView!

func mapView(_ ProfileMapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation.isMember(of: MKUserLocation.self) {
        return nil
    }

    let reuseId = "ProfilePinView"

    var pinView = ProfileMapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if pinView == nil {
        pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    }
    pinView!.canShowCallout = true
    pinView!.image = UIImage(named: "CustomPinImage")
    return pinView
}

override func viewDidLoad() {
    super.viewDidLoad()
    let LightHouseLocation = CoordinatesTemplate
    // Drop a pin
    let lightHouse = MKPointAnnotation()
    lightHouse.coordinate = LightHouseLocation
    lightHouse.title = barNameTemplate
    lightHouse.subtitle = streetNameTemplate
    ProfileMapView.addAnnotation(lightHouse)
}

为什么它不起作用?为什么我无法将自定义图像作为图像?它适用于我的另一个视图控制器。 提前谢谢

1 个答案:

答案 0 :(得分:2)

您的问题是,您错过了将UIViewController添加为MKMapView的代表,因此您需要在viewDidLoad中添加此行,正如我在评论中所说的那样

self.ProfileMapView.delegate = self

我还建议您使用扩展程序模式使代码更具可读性

extension YourViewController : MKMapViewDelegate{

    func mapView(_ ProfileMapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if annotation.isMember(of: MKUserLocation.self) {
            return nil
        }

        let reuseId = "ProfilePinView"

        var pinView = ProfileMapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if pinView == nil {
            pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)}
        pinView!.canShowCallout = true
        pinView!.image = UIImage(named: "CustomPinImage")

        return pinView

    }
}