我一直在跟随Xcode的教程(链接),直到我接触到MapView"部分,此时我被指示使用Map(coordinateRegion: $region)
。我在Mac Mini上运行Xcode 12.4,只能运行到macOS 10.15,所以我收到了'Map' is only available in macOS 11.0 or newer
的错误。我试着浏览苹果的文档,寻找与我的MacOS版本对应的代码,但我找不到。我可以使用哪些等效代码来完成本教程的这一部分?
完整示例代码:
import SwiftUI
import MapKit
struct MapView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
var body: some View {
Map(coordinateRegion: $region)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
您需要将MKMapView
包裹在NSViewRepresentable
中。
下面是它的一个基本表示。注意,SwiftUI 2.0Map
可以做更多的事情,但这将使您开始使用您所显示的示例代码:
struct MapView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)
var body: some View {
MapCompat(coordinateRegion: $region)
}
}
struct MapCompat : NSViewRepresentable {
@Binding var coordinateRegion : MKCoordinateRegion
func makeNSView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
return mapView
}
func updateNSView(_ view: MKMapView, context: Context) {
view.region = coordinateRegion
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator : NSObject, MKMapViewDelegate {
var parent : MapCompat
init(_ parent: MapCompat) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
DispatchQueue.main.async {
self.parent.coordinateRegion = mapView.region
}
}
}
}
更新以修复我的初始错误的UIKit (uiviewrepresable)等效这个而不是AppKit (nsviewrepresable)