3

我正在尝试将清单 6-9MKPolygon中 MapKit参考中的 Objective-C 代码转换为 Swift。

当我使用

 init(coordinates:count:)

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

调用中缺少参数“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)
        }

似乎摆脱了编译器错误,但仍然没有添加覆盖。

4

1 回答 1

4

存在的问题:

var poly: MKPolygon = MKPolygon(points, 4)

是它没有为初始化程序提供参数标签,也没有points作为指针传递。

将行更改为:

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


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


另请注意,这var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()会创建一个数组。这样做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:)初始化程序作为第一个参数的结构。

于 2014-08-05T01:33:24.170 回答