检查mapView是否已完成渲染?

时间:2018-01-29 18:20:04

标签: swift mapkit mkmapview

所以我知道swift有mapViewDidFinishRenderingMap(_:fullyRendered:),但我不知道如何使用该函数在完成渲染时只将mapView添加到视图层次结构中。

现在,即使使用DispatchGroup .enter().leave()view.addSubview(mapView)也会在完成渲染之前被调用,这会导致我的MKPolylines没有在加载时显示在地图上。

如何在调用view.addSubview(mapView)之前确保地图完成渲染?

@Koen基本上是我的viedDidLoad()正在做的事情:

override func viewDidLoad() {
    super.viewDidLoad()
    mapView = MKMapView()

    let leftMargin:CGFloat = 0
    let topMargin:CGFloat = 0
    let mapWidth:CGFloat = view.frame.size.width
    let mapHeight:CGFloat = view.frame.size.height

    mapView?.frame = CGRect(x: leftMargin, y: topMargin, width: mapWidth, height: mapHeight)

    mapView?.mapType = MKMapType.standard
    mapView?.isZoomEnabled = true
    mapView?.isScrollEnabled = true

    mapView?.delegate = self
    mapView?.showsScale = true

    // I have this to make sure they run in order only after the previous block is finished because of dependencies
    let group = DispatchGroup()
    group.enter()
    DispatchQueue.main.async {
        // gets the routes as polylines and adds to mapView
        self.fetchRoutes()
        group.leave()
    }
    goup.notify(queue: .main) {
        group.enter()
        DispatchQueue.main.async {
            // depending on the route data, adds the stops as annotations to mapView
            self.fetchAnnotations()
            group.leave()
        }
        group.notify(queue: .main) {
            // the idea was that once both route and stops are added to the mapView, display mapView to screen
            self.view.addSubview(mapView)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

通过将所有数据提取代码移动到单个函数中并使用DispatchGroup仅在提取完成后调用addSubview(mapView)来解决问题。

无法找出根本原因,但问题已经解决。