【问题标题】:Cant set Custom Pin Image In MapView, Swift 3无法在 MapView,Swift 3 中设置自定义图钉图像
【发布时间】:2017-08-25 21:54:07
【问题描述】:

小地图代码:

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)
}

为什么它不起作用?为什么我不能让我的自定义图像用作 pin 图像?它适用于我的另一个视图控制器。 先谢谢了

【问题讨论】:

  • 您是否将 viewController 设置为地图委托?
  • 这是什么意思?
  • 在你的视图中添加DidLoad这一行self.ProfileMapView.delegate = self
  • 如果能解决您的问题,请告诉我@RandomGeek
  • 它做到了!谢谢 !你能把它作为一个答案,这样我就可以标记为正确了

标签: ios swift annotations mapkit mkpinannotationview


【解决方案1】:

您的问题是您缺少将您的 UIViewController 添加为您的 MKMapView 的代表,因此您需要在您的 viewDidLoad 中添加这一行,正如我在 cmets 中所说的那样

self.ProfileMapView.delegate = self

我还建议您使用 extension 模式来使您的代码更具可读性

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

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多