SwiftUI 按钮与地图交互

SwiftUI Button interact with Map

我是 Swift 和 SwiftUI 的新手,对于一个项目组,我需要开发我的第一个 IOS 应用程序。

我可以使用 Mapbox 显示地图,但我不知道如何在单击按钮时关注我的用户。

我不知道如何将我的按钮与我的结构 MapView 交互

这是我的代码:

MapView.swift:

import Mapbox

struct MapView: UIViewRepresentable {

    let mapView: MGLMapView = MGLMapView(frame: .zero)

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
        mapView.delegate = context.coordinator
        return mapView
    }

    func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) {

    }

    func styleURL(_ styleURL: URL) -> MapView {
        mapView.styleURL = styleURL
        return self
    }

    func centerCoordinate(_ centerCoordinate: CLLocationCoordinate2D) -> MapView {
        mapView.centerCoordinate = centerCoordinate
        return self
    }

    func zoomLevel(_ zoomLevel: Double) -> MapView {
        mapView.zoomLevel = zoomLevel
        return self
    }

    func userTrackingMode(_ userTrackingMode: MGLUserTrackingMode) -> MapView {
        mapView.userTrackingMode = userTrackingMode
        return self
    }
}

class Coordinator: NSObject, MGLMapViewDelegate {
    var parent: MapView

    init(_ parent: MapView) {
        self.parent = parent
    }
}

ContentView.swift:

import Mapbox

struct ContentView: View {

    @Environment(\.colorScheme) var colorScheme: ColorScheme

    var body: some View {
        ZStack {
            MapView()
                .userTrackingMode(.follow)
                .edgesIgnoringSafeArea(.all)
            HStack(alignment: .top) {
                Spacer()
                VStack() {
                    Button(action: {
                        //ACTION TO CHANGE FOLLOW MODE
                    }) {
                        Image(systemName: "location.fill")
                            .frame(width: 40.0, height: 40.0)
                    }
                    .padding(.top, 60.0)
                    .padding(.trailing, 10.0)
                    .frame(width: 45.0, height: 80.0)
                    Spacer()
                }

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.colorScheme, .dark)
    }
}

非常感谢!

实际上我认为在你的情况下,因为你有对地图的引用,你可以尝试直接与它交互(又名命令式,因为它本质上就是这样,所以不需要把简单的事情复杂化)

喜欢

...

let myMapHolder = MapView()
var body: some View {
    ZStack {
        myMapHolder
            .userTrackingMode(.follow)
            .edgesIgnoringSafeArea(.all)
    ...



       VStack() {
            Button(action: {
                self.myMapHolder.mapView.userTrackingMode = _your_mode_
            }) {
                Image(systemName: "location.fill")