iOS MKMapView自定义图像显示在左上角

时间:2016-09-01 13:55:17

标签: ios swift mkmapview

我使用iOS MKMapView在地图上将图像显示为标记图标。问题是图像总是显示在屏幕的左上角。如果我触摸屏幕或稍微移动地图,图像会在正确的gps位置正确显示。 如果我不使用自定义图像,则会在正确的位置正确显示引脚/标记。

这是代码:

func addAnnotationsToMap()
{
    self.mapView.removeAnnotations(self.mapView.annotations)
    for post in self.posts
    {
        let gps = CLLocationCoordinate2D(latitude: post.GPS!.latitude!, longitude: post.GPS!.longitude!)
        let postPin = PostAnnotation(gps: gps)
        self.mapView.addAnnotation(postPin)
     }
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
    if (annotation is MKUserLocation)
    {
        return nil
    }

    let postAnnotation = annotation as! PostAnnotation
    let reuseId = "customAnnotationView"
    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil
    {
        anView = createCustomIconView(postAnnotation)
    }
    else
    {
        anView!.annotation = annotation
    }
    return anView
}

func createCustomIconView(postAnnotation:PostAnnotation) -> CustomAnnotationView
{
    let w = (UIScreen.mainScreen().bounds.size.width) / 8
    let h = w
    let customIconView = CustomAnnotationView(frame: CGRectMake(0, 0, w, h))
    customIconView.imageView.image = UIImage(imageLiteral: postAnnotation.picName!)
    customIconView.annotation = postAnnotation
    return customIconView
}

1 个答案:

答案 0 :(得分:2)

信不信由你,删除view.translatesAutoresizingMaskIntoConstraints = false

后修复了问题

这个答案的灵感来自MKViewMap custom annotation disappears on click