我使用MapKit实现了Apple SwiftUI教程的一个略有更改的版本。
当我运行它时,我会收到错误消息,并调整我得到的相应视图的大小:
[SwiftUI] NSHostingView is being laid out reentrantly while rendering its SwiftUI content. This is not supported and the current layout pass will be skipped.
查看调用代码:
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结构:
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])
}
}
}
收到了同样的消息,并拼命尝试在main.sync中进行第一次调度,但在运行时出现了异常。
然后我简单地尝试了异步。
{
let region = MKCoordinateRegion(center: visibleArea.coordinate,
latitudinalMeters: 200, longitudinalMeters: 200)
DispatchQueue.main.async
{
nsView.setRegion(region, animated: false)
}
}
也适用于动画
DispatchQueue.main.async
{
nsView.setRegion(region, animated: true)
}
事实上,这已经成功了:它删除了
- Xcode中的紫色信息消息(12.3(
- 删除控制台消息
希望在苹果清理之前这只是一个小补丁(或解释原因(。