SwiftUI Map在中心更改后不更新



我不确定为什么当我更新mapRegion时我的SwiftUI地图正在更新。以一个新的坐标为中心。坐标,但当我用locationManager值更新它时不是。如果我运行下面的代码,首先当一个点。使用了坐标,地图就会毫无问题地移动&我看到地图变了。如果我在没有空位的时候运行它& &;传入一个位置,但是,我不会从地图的0,0坐标移动。

.onAppear {
print("mapRegion.center BEFORE = (mapRegion.center)")
annotations = [Annotation(name: spot.name, address: spot.address, coordinate: spot.coordinate)]
if spot.id != nil { // If we have a spot, make that the center, otherwise continue to use user location
mapRegion.center = spot.coordinate
} else {
guard let newCenter = locationManager.location?.coordinate else {
print("*** Couldn't get proper newCenter")
return
}
mapRegion.center = newCenter
}
print("mapRegion.center AFTER = (mapRegion.center)")
}

第一个和第二个案例的输出显示了更新:

mapRegion.center BEFORE = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
mapRegion.center AFTER = CLLocationCoordinate2D(latitude: 42.66078178848971, longitude: -70.61446845531464)
mapRegion.center BEFORE = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
mapRegion.center AFTER = CLLocationCoordinate2D(latitude: 42.335795, longitude: -71.17047933673686)

任何关于mapRegion的想法都被绑定到地图上作为坐标区域。

谢谢你的建议!

不知道为什么,但是如果我把代码更新mapRegion。在Task{}块中的locationManager中,它现在可以工作了。令人惊讶,因为print语句显示了更新。还需要注意的是,如果我在Task块中包装所有内容,我会得到"紫色警告"。关于"在视图更新期间修改状态,这将导致未定义的行为。">

.onAppear {
annotations = [Annotation(name: spot.name, address: spot.address, coordinate: spot.coordinate)]
if spot.id != nil { // If we have a spot, make that the center, otherwise continue to use user location
mapRegion.center = spot.coordinate
} else {
Task {
mapRegion.center = locationManager.location?.coordinate ?? CLLocationCoordinate2D()
}
}
}

最新更新