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

iOS MKMapView自定义图像显示在左上角,ios,swift,mkmapview,Ios,Swift,Mkmapview,我使用iOS MKMapView将图像显示为地图上的标记图标。问题是图像总是显示在屏幕的左上角。如果我触摸屏幕或稍微移动地图,图像将正确显示在正确的gps位置。 如果不使用自定义图像,则管脚/标记将正确显示在正确的位置 代码如下: func addAnnotationsToMap() { self.mapView.removeAnnotations(self.mapView.annotations) for post in self.posts { let

我使用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
}

信不信由你,删除视图后问题已经解决。translatesAutoresizingMaskIntoConstraints=false


这个答案的灵感来自

您是否尝试过使用其他初始值设定方法?类似于
CustomAnnotationView(注释:postAnnotation,reuseIdentifier:“CustomAnnotationView”)
而不是
CustomAnnotationView(框架:CGRectMake(0,0,w,h))
?谢谢你的建议,我在下面发布了答案。这里也有同样的问题。我在一些子视图上做一些自定义绘图,遇到了同样的问题。我所经历的是,当我放大或缩小一点时,所有的注释都会在左上角闪烁和聚集,然后返回原位。删除这一行后:view.translatesAutoresizingMaskIntoConstraints=false解决了我的问题。非常感谢!