我创建了一个名为“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的实现看起来错误。 –