我试图将Listing 6-9中MapKit MKPolygon
引用中的Objective-C代码转换为Swift。
当我使用
调用该函数时 init(coordinates:count:)
init函数,我收到错误:
缺少参数' 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)
}
似乎摆脱了编译器错误,但仍然没有添加叠加层。
答案 0 :(得分: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
}
不相关:而不是调用数组points
,coordinates
可能会更好,因为points
意味着数组可能包含MKMapPoint
结构,这是(points:count:)
初始化程序所采用的结构第一个论点。