我創建了一個名爲「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
對於我的每個註釋都會被多次觸發,但不會在屏幕上顯示任何內容。
你是如何添加MKAnnotation的?你能告訴我們代碼嗎? –
你需要展示更多的代碼。顯示您將任何註釋添加到地圖視圖的位置。顯示PlaceAnnotationView。另請注意,對於註解視圖重用的情況,'viewForAnnotation'的實現看起來是錯誤的;您無法設置註釋視圖的「註釋」。 – matt
@matt我更新了代碼。我不確定我是否理解viewForAnnotation的實現看起來錯誤。 –