ios - 将图像添加到 MKAnnotationView 会取代 pin

标签 ios swift mkannotation 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")
            pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            pinView!.canShowCallout = true
            pinView.image = UIImage(named: "stopIcon")
        }
        return pinView

    }
    return nil
}

示例 enter image description here enter image description here

我尝试使用的图像: enter image description here

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

最佳答案

代码正在使用自定义图像创建 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
}

关于ios - 将图像添加到 MKAnnotationView 会取代 pin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799174/

相关文章:

ios - UISwitch 在 iOS map 标注中无响应

swift - 将数据从 MKAnnotationView 传递到 UICollectionViewController

ios - 如何使 UIbutton 仅在写入文本时出现?

ios - Xcode 自动完成建议 NSArray getter 神秘的 "songsAtIndexes"

ios - 在后台 Swift 中播放 YouTubePlayer 声音

ios - 创建一个转换,当 View 被移除时,它的移除依赖于 @State 值

iOS mkmap - 放大/缩小时 map 跳跃的动画注释

ios - 根据 iOS 环境主题自动在浅色和深色之间更改 iOS 应用程序主题

ios - 我没有收到 GPS 位置更新。我错过了什么?

swift - Quickbooks 创建一个 TimeActivity