How can I add a MapView to another View in Swift?

99封情书 提交于 2021-01-29 14:01:29

问题


I have 2 tabs in my application. On the first one, I display a View (which is myView, a self defined struct) and on the second one I want to display a MapView. I found several tutorials, showing how to add a MapView via Storyboard, but I don't get how I can finally display it in one of my Tabs. The tabs are created as follows:

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)
        }
    }
}

I want to insert the Map instead of the now placed "Text("MAP")".


回答1:


You can use any views that were previously supported within UIKit (or this case, MapKit) within SwiftUI, you just have to provide a bridging class conforming to UIViewRepresentable.

I recommend taking a look at Apple's provided tutorials at: https://developer.apple.com/tutorials/swiftui/tutorials

Here's an example of the class that does what you want:

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)
    }
}

Then, within your view above, you can replace the Text("MAP") with MapView(coordinate: center-coordinate-here)



来源:https://stackoverflow.com/questions/59686365/how-can-i-add-a-mapview-to-another-view-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!