【发布时间】:2019-07-25 23:41:35
【问题描述】:
我正在尝试更改地图上现有 MKOverlay 的颜色。
我添加了几个 MKPolygons 作为 mapView 的唯一叠加层。在渲染它们时,叠加层的颜色由 mapView rendererFor 函数应用。
我想定期更改现有叠加层的颜色;理想情况下无需删除所有并重新添加。我有可以处理颜色变化的代码,但我不知道如何识别不同的叠加层,除了它们的类型(MKPolygon,MKCircle) - 但在我的情况下,所有叠加层都是 MKPolygon,所以执行代码只会改变所有内容。
- 在使用 addOverlay 和操作标题之前,我尝试将 MKPolygon 转换为 MKOverlay,但标题是“仅获取”
- 我曾尝试子类化 MKPolygon,但我的阅读表明这在 Swift 中很糟糕。
我像这样添加叠加层。
var shapeNW:MKMapPoint = MKMapPoint( CLLocationCoordinate2D(latitude: 48.313319, longitude: -124.109715))
var shapeNE:MKMapPoint = MKMapPoint( CLLocationCoordinate2D(latitude: 48.313312, longitude: -124.108695))
var shapeSW:MKMapPoint = MKMapPoint( CLLocationCoordinate2D(latitude: 48.312661, longitude: -124.109767))
var shapeSE:MKMapPoint = MKMapPoint( CLLocationCoordinate2D(latitude: 48.312626, longitude: -124.108679))
var myShapePoints:[MKMapPoint] = [shapeNW,shapeNE,shapeSE,shapeSW]
// addAnItemToMap(title: "Circle", locationName: "CircleName", type: "SS", coordinate: feiLocation, horizontalAccuracy: 20)
var myShape:MKPolygon = MKPolygon(points: myShapePoints, count: 4)
mapView.addOverlay(myShape)
这是我用来在创建颜色后更改颜色的函数。但很明显,这个函数会改变所有项目的颜色,因为它无法识别要更改的叠加层。这是我的问题,我想确定特定的叠加层并对其进行更改。
func changeColor(identifier: String) {
let overlays = self.mapView.overlays
let duration:TimeInterval = 5.0
for overlay in overlays {
if identifier == "on"{
let renderer = mapView.renderer(for: overlay) as! MKPolygonRenderer
DispatchQueue.main.async{
renderer.alpha = 1.0
renderer.fillColor = UIColor.blue
}
}
else {
let renderer = mapView.renderer(for: overlay) as! MKPolygonRenderer
DispatchQueue.main.async{
renderer.alpha = 0.0
}
}
}
}
【问题讨论】: