如何在Swift中使用MKPolylineView
我想在Swift应用程序中绘制折线。
SWIFT代码
class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet var theMapView: MKMapView override func viewDidLoad() { super.viewDidLoad() setMapView() } func setMapView() { //theMapView.zoomEnabled = false //theMapView.scrollEnabled = false theMapView.rotateEnabled = false // var lat: CLLocationDegrees = 37.586601 var lng: CLLocationDegrees = 127.009381 // var latDelta: CLLocationDegrees = 0.008 var lngDelta: CLLocationDegrees = 0.008 var theSpan: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lngDelta) var initLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng) var theRegion: MKCoordinateRegion = MKCoordinateRegionMake(initLocation, theSpan) self.theMapView.setRegion(theRegion, animated: true) var locations = [CLLocation(latitude: 37.582691, longitude: 127.011186), CLLocation(latitude: 37.586112,longitude: 127.011047), CLLocation(latitude: 37.588212, longitude: 127.010438)] var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate}) var polyline = MKPolyline(coordinates: &coordinates, count: locations.count) var myPolylineView : MKPolylineView /* error */ myPolylineView.polyline = polyline // #1 myPolylineView.strokeColor = UIColor.blueColor() // #2 myPolylineView.lineWidth = 5; // #3 self.theMapView.addOverlay(myPolylineView) // #4 /* ----- */ } }
错误:
// #1 <br> Cannot assign to 'polyline' in 'myPolylineView' <br> // #2 <br> 'strokeColor' is unvailable: APIs deprecated as iOS 7 and earlier are unavailable in Swift <br> // #3 <br> 'lineWidth' is unvailable: APIs deprecated as iOS 7 and earlier are unavailable in Swift <br> // #4 <br> Missing argument for parameter 'level' in call <br>
我无法find解决办法。
首先 ,而不是MKPolylineView
,您必须创build一个MKPolylineRenderer
。
MKPolylineView
自iOS 7以来一直被弃用,尽pipe如果必要的话,仍然可以在Objective-C中使用它,但它在Swift中不受支持。
其次 ,您必须在rendererForOverlay
委托方法中创build并返回一个MKPolylineRenderer
(不传递给addOverlay
)。
在addOverlay
方法中,传递MKPolyline
对象(不是MKPolylineView
或MKPolylineRenderer
)。
(请参阅将MKOverlayPathRenderer添加为MKMapView获取exception ,以解释您传递给addOverlay
对象与您在rendererForOverlay
返回的对象之间的区别。)
所以在setMapView
方法中,删除创build和设置myPolylineView
的行,并将addOverlay
行更改为:
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 }
确保地图视图的delegate
被设置,否则委托方法将不会被调用,叠加层将不会出现。 如果theMapView
是IBOutlet,则连接delegate
出口或将其设置为代码(例如,在调用super之后在viewDidLoad
):
self.theMapView.delegate = self