【问题标题】:iOS MKMapView custom images display on top left corneriOS MKMapView 自定义图像显示在左上角
【发布时间】:2016-09-02 11:26:53
【问题描述】:

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

【问题讨论】:

  • 您是否尝试过使用其他初始化方法?像CustomAnnotationView(annotation: postAnnotation, reuseIdentifier: "customAnnotationView") 而不是CustomAnnotationView(frame: CGRectMake(0, 0, w, h))
  • 感谢您的建议,我在下面发布了答案。

标签: ios swift mkmapview


【解决方案1】:

不管你信不信,我删除 view.translatesAutoresizingMaskIntoConstraints = false 后问题就解决了

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

【讨论】:

  • 这里有同样的问题。我正在对一些子视图进行一些自定义绘图并且遇到了同样的问题。我所经历的是,当我稍微放大或缩小时,所有注释都会闪烁并聚集在左上角,然后最终会回到原位。删除这一行后: view.translatesAutoresizingMaskIntoConstraints = false 它解决了我的问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多