2017-02-20 36 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我忘了設置註釋的座標:) –