在 SwiftUI 中,你可以使用 MapKit 中的 MKMapView 来显示地图视图。
以下是示例代码:
import MapKit
import SwiftUI
struct MapView: UIViewRepresentable {
let coordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ uiView: MKMapView, context: Context) {
let span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
let region = MKCoordinateRegion(center: coordinate, span: span)
uiView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
uiView.addAnnotation(annotation)
}
}
这个代码定义了一个名为 MapView 的 UIViewRepresentable 结构体来显示地图视图。该结构体接收一个 CLLocationCoordinate2D 类型的坐标,然后使用 MapKit 来创建一个 MKMapView。
在 makeUIView 方法中,我们创建了一个 MKMapView 对象,并将其返回。
在 updateUIView 方法中,我们设置了地图视图的中心和缩放级别,然后将一个 MKPointAnnotation 对象添加到这个位置上。
最后,在 SwiftUI 视图中使用 MapView 视图,如下所示:
struct ContentView: View {
let coordinate = CLLocationCoordinate2D(latitude: 37.33233141, longitude: -122.0312186)
var body: some View {
MapView(coordinate: coordinate)
}
}
这个代码创建了一个名为 ContentView 的 SwiftUI 视图,并传递了一个坐标给 MapView 视图来显示这个位置的地图视图。