MapKit Error: NSHostingView is being laid out reentrantly while rendering its SwiftUI content
Asked Answered
H

1

7

I have implemented a slightly changed version of the Apple SwiftUI tutorial using MapKit.

When I run it I get the error message and resize the corresponding view I get:

[SwiftUI] NSHostingView is being laid out reentrantly while rendering its SwiftUI content. This is not supported and the current layout pass will be skipped.

View calling code:

    MapView(coordinate: location?.coordinates)
        .frame(minHeight: 200)
        .overlay(
            GeometryReader{
                proxy in
                Button("Open in Maps") {
                    if (self.location?.coordinates != nil){
                        let destination = MKMapItem(placemark: MKPlacemark(coordinate: self.location!.coordinates))
                        destination.name = "the car"
                        destination.openInMaps()
                    }
                }
                .frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottomTrailing)
                .offset(x: -10, y: -10)
            }
    )

MapView struct:

import SwiftUI
import MapKit

/// a view containing the map
struct MapView: NSViewRepresentable {
    
    /// the location coordinates
    var coordinate: CLLocationCoordinate2D?
    
    func makeNSView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
    
    func updateNSView(_ nsView: MKMapView, context: Context) {
        let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
        var region: MKCoordinateRegion = MKCoordinateRegion()
        if (self.coordinate != nil){
            region = MKCoordinateRegion(center: coordinate!, span: span)
        }
        nsView.setRegion(region, animated: true)
        if ((nsView.annotations.count == 0) && (self.coordinate != nil)){
            let locationPin: MKPointAnnotation = MKPointAnnotation()
            locationPin.coordinate = coordinate!
            nsView.addAnnotations([locationPin])
        }
    }
}
Housekeeper answered 29/8, 2020 at 12:25 Comment(0)
C
4

Got the same message and desperately tried first dispatch in main.sync but got exceptions at runtime.

Then I simply tried async.

   {
      let region = MKCoordinateRegion(center: visibleArea.coordinate,
                                                latitudinalMeters: 200, longitudinalMeters: 200)
      DispatchQueue.main.async
      {
         nsView.setRegion(region, animated: false)
      }
   }

works also with animation

      DispatchQueue.main.async
      {
         nsView.setRegion(region, animated: true)
      }

Actually that did the trick for now: it remove

  1. the violet information message in Xcode (12.3)
  2. remove the console message

Hope that is only a little patch until Apple clean it up (or explain why).

Chlortetracycline answered 16/1, 2021 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.