我在设置为MKMapView
的 SwiftUI 中显示 a 时遇到问题。我正在显示一张地图:userTrackingMode
.follow
struct ContentView: View {
var body: some View {
MapView()
}
}
在这MapView
我(a)设置userTrackingMode
和(b)确保我有使用时的权限。我一直在基于故事板的项目中使用这种模式。无论如何,MapView
现在看起来像:
final class MapView: UIViewRepresentable {
private lazy var locationManager = CLLocationManager()
func makeUIView(context: Context) -> MKMapView {
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
let mapView = MKMapView()
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow // no better is mapView.setUserTrackingMode(.follow, animated: true)
return mapView
}
func updateUIView(_ uiView: UIViewType, context: Context) {
print(#function, uiView.userTrackingMode)
}
}
这里一切看起来都不错,但地图(在模拟器和物理设备上)实际上并未处于跟随用户跟踪模式。
所以,我在上面进行了扩展,添加了一个采用MKMapViewDelegate
协议的协调器,这样我就可以看到跟踪模式发生了什么:
final class MapView: UIViewRepresentable {
private lazy var locationManager = CLLocationManager()
func makeUIView(context: Context) -> MKMapView {
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow // no better is mapView.setUserTrackingMode(.follow, animated: true)
return mapView
}
func updateUIView(_ uiView: UIViewType, context: Context) {
print(#function, uiView.userTrackingMode)
}
func makeCoordinator() -> MapViewCoordinator {
return MapViewCoordinator(self)
}
}
class MapViewCoordinator: NSObject {
var mapViewController: MapView
var token: NSObjectProtocol?
init(_ control: MapView) {
self.mapViewController = control
}
}
extension MapViewCoordinator: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
print(#function, mode)
}
}
这导致:
mapView(_:didChange:animated:) MKUserTrackingMode.follow updateUIView(_:context:) MKUserTrackingMode.follow mapView(_:didChange:animated:) MKUserTrackingMode.none
发生了一些事情正在重置userTrackingMode
to .none
。
对于咯咯笑和笑容,我尝试了 reset userTrackingMode
,但这并没有更好:
func updateUIView(_ uiView: UIViewType, context: Context) {
print(#function, uiView.userTrackingMode)
uiView.userTrackingMode = .follow
}
不过,这种笨拙的模式确实有效:
func updateUIView(_ uiView: UIViewType, context: Context) {
print(#function, uiView.userTrackingMode)
DispatchQueue.main.async {
uiView.userTrackingMode = .follow
}
}
userTrackingMode
或者在此初始过程之后重置后者的任何东西似乎也可以工作。
我做错了UIViewRepresentable
什么吗?中的错误MKMapView
?
这不是很相关,但这是我显示跟踪模式的例程:
extension MKUserTrackingMode: CustomStringConvertible {
public var description: String {
switch self {
case .none: return "MKUserTrackingMode.none"
case .follow: return "MKUserTrackingMode.follow"
case .followWithHeading: return "MKUserTrackingMode.followWithHeading"
@unknown default: return "MKUserTrackingMode unknown/default"
}
}
}