iOS MKMapView custom images display on top left co

2020-04-17 05:51发布

问题:

I use iOS MKMapView to show images as marker icons on the map. The problem is the images are always displayed on the top left corner of the screen. If I touch the screen or move the map a little bit, the images show correctly at the right gps locations. If I don't use custom images, the pins/markers are displayed correcly at the right location.

here is the code:

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:

Believe it or not, the problem is fixed after I delete view.translatesAutoresizingMaskIntoConstraints = false

This answer is inspired from MKViewMap custom annotation disappears on click