覆盖注释

时间:2017-07-05 19:49:05

标签: swift annotations mkoverlay mkcircle

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

1 个答案:

答案 0 :(得分:4)

MKCircleMKOverlay个对象。您只需将其添加为叠加层:

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

当然,您必须通过在委托中实施mapView(_:rendererFor:)来告诉地图如何呈现它,并为作为叠加层传递的MKCircleRenderer实例化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")
    }
}