简体   繁体   English

iOS Swift MKMapView删除地图图块

[英]iOS Swift MKMapView remove map tiles

In my app I want to display the annotations on a MKMapView, but I don't want the user to see the map tiles, I want them to be completely black. 在我的应用程序中,我想在MKMapView上显示注释,但是我不希望用户看到地图图块,而是希望它们完全是黑色的。 How can I achieve that look? 我如何获得那种外观?

The mechanism of replacing the map tiles is based on the MKOverlayRenderer class. 替换地图图块的机制基于MKOverlayRenderer类。 You need make your own MKOverlayRenderer subclass where you can customise the displaying of the map tiles. 您需要创建自己的MKOverlayRenderer子类,在其中可以自定义地图图块的显示。 In the ViewController where you are using your map, you need to add an overlay to your MKMapView to trigger the MKMapViewDelegate's rendering method. 在使用地图的ViewController中,您需要向MKMapView添加一个叠加层以触发MKMapViewDelegate的呈现方法。

Example code: 示例代码:

//Subclass of MKOverlayRenderer to tint the tiles
class MyCustomOverlayRenderer: MKOverlayRenderer {
    override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
        let drawRect = self.rect(for: mapRect)
        context.setFillColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
        context.fill(drawRect)
    }
}

//Custom View Controller where the map can be found
class ViewController: UIViewController {

        @IBOutlet weak var mapView: MKMapView!

        override func viewDidLoad() {
            super.viewDidLoad()

            self.mapView.delegate = self

            let tiles = MKTileOverlay(urlTemplate: nil)
            tiles.canReplaceMapContent = true
            self.mapView.add(tiles)
       }

       //Custom method to add an annotation onto your mapView
       @IBAction func mapViewTapped(_ sender: Any) {

            let annotation = MyCustomAnnotation(coordinate: self.mapView.centerCoordinate, title: "MyAnnotation")
            self.mapView.addAnnotation(annotation)
        }
}

extension ViewController : MKMapViewDelegate
{
    //use your custom renderer to render all tiles
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        return MyCustomOverlayRenderer(overlay: overlay)
    }

    //show a pin in the middle of you map
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        return nil
    }
}

And the result is: 结果是:

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM