如何在Swift中将MapView添加到另一个视图?

问题描述 投票:0回答:1

我的应用程序中有2个标签。在第一个窗口上,我显示一个View(即myView,一个自定义结构),在第二个窗口上,我想要显示一个MapView。我找到了一些教程,展示了如何通过Storyboard添加MapView,但是我不知道如何最终在一个Tab中显示它。选项卡创建如下:

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“)”。

swift mkmapview
1个回答
0
投票

您可以使用SwiftUI内UIKit(或本例中的MapKit)以前支持的任何视图,您只需要提供一个符合UIViewRepresentable的桥接类即可。

我建议在以下位置查看Apple提供的教程:https://developer.apple.com/tutorials/swiftui/tutorials

这是一个可以满足您需求的类的示例:

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)

© www.soinside.com 2019 - 2024. All rights reserved.