leachim
leachim

Reputation: 332

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

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")".

Upvotes: 1

Views: 1158

Answers (1)

binaryPilot84
binaryPilot84

Reputation: 1032

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)

Upvotes: 4

Related Questions