2017-02-20 38 views
-2

我创建了一个名为“PlaceAnnotationView”的自定义注解视图,如下图所示:AnnotationView不显示

import Foundation 
import MapKit 

class PlaceAnnotationView : MKPinAnnotationView { 

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) { 

     super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) 

    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
} 

然后在viewForAnnotation我回到我的自定义标注视图,如图所示:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 

     if annotation is MKUserLocation { 
      return nil 
     } 

     var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "PlaceAnnotationView") 

     if annotationView == nil { 
      annotationView = PlaceAnnotationView(annotation: annotation, reuseIdentifier: "PlaceAnnotationView") 
      annotationView?.canShowCallout = true 
     } 

     return annotationView 
} 

下面是代码添加注释:

private func populateNearByPlaces() { 

     var region = MKCoordinateRegion() 
     region.center = CLLocationCoordinate2D(latitude: self.mapView.userLocation.coordinate.latitude, longitude: self.mapView.userLocation.coordinate.longitude) 

     let request = MKLocalSearchRequest() 
     request.naturalLanguageQuery = self.selectedCategory 
     request.region = region 

     let search = MKLocalSearch(request: request) 
     search.start { (response, error) in 

      guard let response = response else { 
       return 
      } 

      for item in response.mapItems { 

       let annotation = PlaceAnnotation() 
       annotation.title = item.name 
       annotation.subtitle = "subtitle" 
       annotation.mapItem = item 

       DispatchQueue.main.async { 
        self.mapView.addAnnotation(annotation) 
       } 


      } 

     } 


    } 

这是代码PlaceAnnotati onView:

import Foundation 
import MapKit 

class PlaceAnnotationView : MKPinAnnotationView { 

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) { 

     super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) 

    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

} 

这里是PlaceAnnotation代码:

进口基金会 进口MapKit

class PlaceAnnotation : MKPointAnnotation { 

    var mapItem :MKMapItem! 

} 

但我没有看到我的任何注释被显示在地图上。 viewForAnnotation对于我的每个注释都会被多次触发,但不会在屏幕上显示任何内容。

+0

你是如何添加MKAnnotation的?你能告诉我们代码吗? –

+0

你需要展示更多的代码。显示您将任何注释添加到地图视图的位置。显示PlaceAnnotationView。另请注意,对于注解视图重用的情况,'viewForAnnotation'的实现看起来是错误的;您无法设置注释视图的“注释”。 – matt

+0

@matt我更新了代码。我不确定我是否理解viewForAnnotation的实现看起来错误。 –

回答

1

根据您选择揭示的代码(看起来很不情愿),似乎问题在于您从未设置注释的coordinate。但注释的coordinate至关重要。这是注释如何告诉它应该在世界的哪个位置,以及与此注释相关联的注释视图如何知道地图上的何处出现。因此,与此注释相关联的注释视图确定而不是知道要在地图上出现的位置。因此它不会出现

+0

谢谢! Yikes我忘了设置注释的坐标:) –