SwiftUI按钮与地图互动 [英] SwiftUI Button interact with Map
问题描述
我对Swift和SwiftUI完全陌生,对于一个项目组,我需要开发我的第一个IOS应用.
I'm totally new with Swift and SwiftUI and for a project group, I need to develop my first IOS app.
我可以使用Mapbox显示地图,但是当我单击按钮时我不知道如何关注用户.
I can display a map with Mapbox but I don't know how to follow my user when I click on a button.
我不知道如何将按钮与结构MapView交互
I don't know how to interact my button with my struct MapView
这是我的代码:
MapView.swift:
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:
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)
}
}
非常感谢!
推荐答案
实际上,在您的情况下,我认为,由于您具有对地图的引用,因此您可以尝试直接与它进行交互(也称为命令式,因为它本质上就是这样) ,因此无需使简单的事情变得复杂)
Actually I think in your case, as you have a reference to map, you can try to interact with it directly (aka imperatively, because it is such by nature, so no need to make simple thing complex)
喜欢
...
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")
这篇关于SwiftUI按钮与地图互动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!