【问题标题】:Adding image to MKAnnotationView displaces pin将图像添加到 MKAnnotationView 会替换 pin
【发布时间】:2014-09-12 01:00:12
【问题描述】:

我正在尝试使用图像删除一些代表巴士站的图钉,当我添加图像时,它会更改图钉的位置。当我没有设置图像时,图钉会放在正确的位置。

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

    if annotation is StopAnnotation {

        let identifier = "stopAnnotation"
        var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
        if pinView == nil {
            //println("Pinview was nil")
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            pinView!.canShowCallout = true
            pinView.image = UIImage(named: "stopIcon")
        }
        return pinView

    }
    return nil
}

示例

我尝试使用的图像:

谁能告诉我为什么会这样?我在此应用的 Obj-C 版本中使用完全相同的图像,一切正常。

【问题讨论】:

    标签: ios swift mkannotation mkannotationview


    【解决方案1】:

    代码正在创建一个带有自定义图像的MKPinAnnotationView

    MKPinAnnotationView 类只能用于显示默认图钉图像。

    要显示自定义图像,最好使用普通的MKAnnotationView


    因为代码使用MKPinAnnotationView,所以图像会自动获得应用到它的偏移量(centerOffset 属性)。

    此内置偏移适用于默认图钉图像,但不适用于您的自定义图像。

    与其尝试覆盖此默认行为,不如使用普通的MKAnnotationView

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    
        if annotation is StopAnnotation {
    
            let identifier = "stopAnnotation"
            var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
            if pinView == nil {
                //println("Pinview was nil")
    
                //Create a plain MKAnnotationView if using a custom image... 
                pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
    
                pinView!.canShowCallout = true
                pinView.image = UIImage(named: "stopIcon")
            }
            else {
                //Unrelated to the image problem but...
                //Update the annotation reference if re-using a view...
                pinView.annotation = annotation
            }
    
            return pinView          
        }
        return nil
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多