且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中使用MKPolylineView

更新时间:2023-02-21 09:40:25

首先,而不是 MKPolylineView ,您必须创建 MKPolylineRenderer

First, instead of MKPolylineView, you must create an MKPolylineRenderer.

自iOS 7以来,MKPolylineView 已被弃用,尽管您仍然可以使用它如果有必要,在Objective-C中,Swift不支持。

MKPolylineView has been deprecated since iOS 7 and, although you can still use it in Objective-C if necessary, it's not supported in Swift.

第二,你必须创建并返回 MKPolylineRenderer rendererForOverlay 委托方法中的(不将其传递给 addOverlay )。

Second, you must create and return an MKPolylineRenderer in the rendererForOverlay delegate method (not pass it to addOverlay).

addOverlay 方法中,您传递 MKPolyline 对象(不是 MKPolylineView MKPolylineRenderer )。

In the addOverlay method, you pass the MKPolyline object (not the MKPolylineView or MKPolylineRenderer).

(参见将MKOverlayPathRenderer作为叠加添加到MKMapView会获得异常,以解释传递给 addOverlay 的对象与中返回的对象之间的区别c> rendererForOverlay 。)

(See Adding MKOverlayPathRenderer as overlay to MKMapView gets exception for an explanation of the difference between what object you pass to addOverlay vs. what object you return in rendererForOverlay.)



所以在 setMapView 方法,删除创建并设置 myPolylineView 的行,并将 addOverlay 行更改为:


So in the setMapView method, remove the lines that create and set myPolylineView and change the addOverlay line to:

self.theMapView.addOverlay(polyline)

然后实现 rendererForOverlay 方法:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
    if overlay is MKPolyline {
        var polylineRenderer = MKPolylineRenderer(overlay: overlay)
        polylineRenderer.strokeColor = UIColor.blueColor()
        polylineRenderer.lineWidth = 5
        return polylineRenderer
    }

    return nil
}

确保设置了地图视图的委托,否则将不会调用委托方法并且不会显示叠加层。如果 theMapView 是一个IBOutlet,请连接委托出口或在代码中设置它(例如在 viewDidLoad 在调用super之后):

Make sure the map view's delegate is set otherwise the delegate method won't get called and the overlay will not appear. If theMapView is an IBOutlet, connect the delegate outlet or set it in code (eg. in viewDidLoad after calling super):

self.theMapView.delegate = self