Use of unresolved identifier 'Map' SwiftUI

放肆的年华 提交于 2021-01-29 09:18:04

问题


I am following the official tutorial for SwiftUI and have run into the error message 'Use of unresolved identifier 'Map'. Even when I copy and and paste the code from the tutorial, it is still giving me the error. I have looked at a few solutions for similar issues and can't seem to find anything that will work. Code below.

import SwiftUI
import MapKit

struct MapView: View {
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 34.011_286, longitude: -116.166_868),
        span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
    )

    var body: some View {
        Map(coordinateRegion: $region)
    }
    }

    struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

I apologise if this is really obvious - but I'm new to Swift/SwiftUI, and can't see where the issue is coming from. Thanks in advance!


回答1:


Problem is related to import MapKit. Because Map is defined in MapKit. Please verify if you are able to import MapKit properly




回答2:


I also got into trouble in this case. So, I make View method using UIViewRepresentable with 2 methods: 'makeUIView' and 'updateUIView'.

MapView

import SwiftUI
import MapKit

struct MapViewUI: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
         MKMapView(frame: .zero)
    }
    func updateUIView(_ view: MKMapView, context: Context) {
            let coordinate = CLLocationCoordinate2D(
                latitude: 2.6540427, longitude: 98.8932576)
            let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
            let region = MKCoordinateRegion(center: coordinate, span: span)
            view.setRegion(region, animated: true)
    }
}

And, You can call your View looks like this

struct MapPageView: View {
    var body: some View {
        VStack {
            MapViewUI()
                .frame(height: 300)
        }
    }
}


来源:https://stackoverflow.com/questions/65438443/use-of-unresolved-identifier-map-swiftui

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