如何将 MapView 添加到 Swift 中的另一个视图?
How can I add a MapView to another View in Swift?
我的应用程序中有 2 个选项卡。在第一个上,我显示一个 View
(这是 myView,一个自定义结构),在第二个上我想显示一个 MapView。我找到了几个教程,展示了如何通过 Storyboard 添加 MapView,但我不知道如何最终在我的一个选项卡中显示它。选项卡创建如下:
struct ContentView: View {
@State private var selection = 0
var body: some View {
TabView(selection: $selection){
myView()
.font(.title)
.tabItem {
VStack {
Image(systemName: "list.dash")
Text("Events")
}
}
.tag(0)
Text("MAP")//here I want the MapView
.tabItem {
VStack {
Image(systemName: "map")
Text("Map")
}
}
.tag(1)
}
}
}
我想插入地图而不是现在放置的 "Text("MAP")"。
您可以在 SwiftUI 中使用 UIKit(或本例中的 MapKit)之前支持的任何视图,您只需提供符合 UIViewRepresentable
的桥接 class。
我建议查看 Apple 提供的教程:https://developer.apple.com/tutorials/swiftui/tutorials
这里有一个 class 的例子,可以满足您的需求:
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var coordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
然后,在您上面的视图中,您可以将 Text("MAP")
替换为 MapView(coordinate: center-coordinate-here)
我的应用程序中有 2 个选项卡。在第一个上,我显示一个 View
(这是 myView,一个自定义结构),在第二个上我想显示一个 MapView。我找到了几个教程,展示了如何通过 Storyboard 添加 MapView,但我不知道如何最终在我的一个选项卡中显示它。选项卡创建如下:
struct ContentView: View {
@State private var selection = 0
var body: some View {
TabView(selection: $selection){
myView()
.font(.title)
.tabItem {
VStack {
Image(systemName: "list.dash")
Text("Events")
}
}
.tag(0)
Text("MAP")//here I want the MapView
.tabItem {
VStack {
Image(systemName: "map")
Text("Map")
}
}
.tag(1)
}
}
}
我想插入地图而不是现在放置的 "Text("MAP")"。
您可以在 SwiftUI 中使用 UIKit(或本例中的 MapKit)之前支持的任何视图,您只需提供符合 UIViewRepresentable
的桥接 class。
我建议查看 Apple 提供的教程:https://developer.apple.com/tutorials/swiftui/tutorials
这里有一个 class 的例子,可以满足您的需求:
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var coordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
然后,在您上面的视图中,您可以将 Text("MAP")
替换为 MapView(coordinate: center-coordinate-here)