2

您好我正在尝试在我的注释周围创建一个叠加层,比如苹果提醒应用程序,我已经创建了一个 MKCircle 对象,我认为我应该使用它来显示叠加层,但是如何将我的 MKCircle 对象转换为一个 MKOVerlay 对象?也许有更好的方法来添加注释?我是 swift 和编程的新手。有什么建议么?

4

1 回答 1

4

MKCircle是一个MKOverlay对象。您只需要将其添加为叠加层:

let circle = MKCircle(center: coordinate, radius: 1000)
mapView.add(circle)

当然,您必须通过mapView(_:rendererFor:)在您的委托中实现来告诉地图如何呈现它,并为作为叠加层传递的 a 实例化MKCircleRenderera MKCircle

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKCircleRenderer(overlay: overlay)
        renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
        renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
        return renderer
    }
}

显然,请确保您也delegate为您的MKMapView. 如果你有其他类型的渲染器,你也可以为它们实现特定的逻辑,例如

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if let circle = overlay as? MKCircle {
            let renderer = MKCircleRenderer(circle: circle)
            renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
            return renderer
        }

        if let polygon = overlay as? MKPolygon {
            let renderer = MKPolygonRenderer(polygon: polygon)
            renderer.fillColor = UIColor.blue.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.blue.withAlphaComponent(0.8)
            return renderer
        }

        if let polyline = overlay as? MKPolyline {
            let renderer = MKPolylineRenderer(polyline: polyline)
            renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.red.withAlphaComponent(0.8)
            return renderer
        }

        fatalError("Unexpected overlay type")
    }
}
于 2017-07-05T20:31:14.193 回答