MKPolygon初始化错误“在调用中缺less参数'interiorPolygons'的参数”/“调用中的额外参数”

我试图将清单6-9中 MapKit MKPolygon引用中的Objective-C代码转换成Swift。

当我用这个函数调用函数

  init(coordinates:count:) 

初始化函数,我得到的错误:

呼叫中缺less参数“interiorPolygons”的参数

当我用interiorPolygons参数调用函数时,出现错误:

在调用中的额外参数

这是我正在使用的代码。

  var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() points[0] = CLLocationCoordinate2DMake(41.000512, -109.050116) points[1] = CLLocationCoordinate2DMake(41.002371, -102.052066) points[2] = CLLocationCoordinate2DMake(36.993076, -102.041981) points[3] = CLLocationCoordinate2DMake(36.99892, -109.045267) var poly: MKPolygon = MKPolygon(points, 4) poly.title = "Colorado" theMapView.addOverlay(poly) 

更新:

  points.withUnsafePointerToElements() { (cArray: UnsafePointer<CLLocationCoordinate2D>) -> () in poly = MKPolygon(coordinates: cArray, count: 4) } 

似乎摆脱了编译器错误,但仍不会添加重叠。

问题在于:

 var poly: MKPolygon = MKPolygon(points, 4) 

是它没有给初始值设定项的参数标签,也没有将points传递给指针。

将该行更改为:

 var poly: MKPolygon = MKPolygon(coordinates: &points, count: 4) 

(更新中的points.withUnsafePointerToElements...版本也可以使用。)

另外请注意, var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()创build一个数组。 做points[0] = ...应该导致运行时错误,因为数组没有开头的元素。 相反,使用points.append()将坐标添加到数组中:

 points.append(CLLocationCoordinate2DMake(41.000512, -109.050116)) points.append(CLLocationCoordinate2DMake(41.002371, -102.052066)) points.append(CLLocationCoordinate2DMake(36.993076, -102.041981)) points.append(CLLocationCoordinate2DMake(36.99892, -109.045267)) 

或者只是一起声明和初始化:

 var points = [CLLocationCoordinate2DMake(41.000512, -109.050116), CLLocationCoordinate2DMake(41.002371, -102.052066), CLLocationCoordinate2DMake(36.993076, -102.041981), CLLocationCoordinate2DMake(36.99892, -109.045267)] 

如果仍然看不到叠加层,请确保已经实现了rendererForOverlay委托方法(并设置或连接了地图视图的delegate属性):

 func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if overlay is MKPolygon { var polygonRenderer = MKPolygonRenderer(overlay: overlay) polygonRenderer.fillColor = UIColor.cyanColor().colorWithAlphaComponent(0.2) polygonRenderer.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) polygonRenderer.lineWidth = 3 return polygonRenderer } return nil } 

不相关:不是调用数组pointscoordinates可能会更好,因为points意味着数组可能包含MKMapPoint结构,这是(points:count:)初始值设定项作为第一个参数的值。