我在故事板中创建了一个MapViewController
类,其中包含MKMapView
的场景。 MKMapView有一个插座mapView
到MapViewController
,并且该插板在故事板中设置为MapViewController
。 MapViewController
是MKMapViewDelegate
,我实现了可选的委托方法mapView:rendererForOverlay
和其他一些方法。
在viewDidAppear
,我致电addMapOverlay
,定义为:
func addMapOverlay() {
let overlayRect = MKMapRectMake(
44.97077, -93.2864435,
0.1, 0.1)
let coordinate = CLLocationCoordinate2DMake(44.97087, -93.2865435)
let overlay = MapOverlay(coordinate: coordinate, rect: overlayRect)
print("adding overlay with level...")
mapView.delegate = self;
mapView.addOverlay(overlay, level: .AboveRoads)
}
即使代理人设置在故事板中,我也试着看看如果我在这里设置它也会有所帮助。 (没有区别。)
我实现了委托方法:
extension MapViewController: MKMapViewDelegate {
func mapViewWillStartRenderingMap(mapView: MKMapView) {
print("mapViewWillStartRenderingMap...")
}
func mapView(mapView: MKMapView, didAddOverlayViews overlayViews: [AnyObject]) {
print("mapView:didAddOverlayViews...")
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay)
-> MKOverlayRenderer {
print("mapView:rendererForOverlay")
if overlay is MapOverlay {
let image = UIImage(named: "main_map_overlay")
let overlayView = MapOverlayView(overlay: overlay, overlayImage: image!)
return overlayView
}
return MKPolylineRenderer()
}
}
我应该在mapView中看到带有坐标的UIImage,但我不知道。问题是mapView:rendererForOverlay
永远不会被调用。缺少什么?我唯一的输出是:
adding overlay with level...
mapViewWillStartRenderingMap...
答案 0 :(得分:2)
我找到了问题的答案。事实证明,CLLocationCoordinate2DMake(44.97087, -93.2865435)
不是在这种情况下制作坐标的正确方法。这样或那样是错误的,因此,在没有任何有用信息的情况下静默添加叠加层会失败。我做了以下事情,现在很好:
let parkTopLeft = MKMapPointForCoordinate(CLLocationCoordinate2D(
latitude: 44.972189,
longitude: -93.287307))
let parkBottomRight = MKMapPointForCoordinate(CLLocationCoordinate2D(
latitude: 44.967810,
longitude: -93.28186))
let overlayRect = MKMapRectMake(
parkTopLeft.x,
parkTopLeft.y,
parkBottomRight.x - parkTopLeft.x,
parkBottomRight.y - parkTopLeft.y)
let coordinate = CLLocationCoordinate2DMake(
overlayRect.origin.x + overlayRect.size.width / 2,
overlayRect.origin.y + overlayRect.size.height / 2)
let overlay = MapOverlay(coordinate: coordinate, rect: overlayRect)
mapView.addOverlay(overlay, level: .AboveRoads)