Я довольно новичок в Swift и SwiftUI, и я хочу добавить кнопку отслеживания пользователей в верхней части вида карты, чтобы при касании текущее местоположение пользователя могло быть в центре экрана. У меня уже есть вид карты и кнопка, но я не смог заставить ее работать.
вот файл ContentView.swift, и я застрял на месте с ****:
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
ZStack {
MapView(locationManager: $locationManager)
.edgesIgnoringSafeArea(.bottom)
HStack {
Spacer()
VStack {
Spacer()
Button(action: {
******
}) {
Image(systemName: "location")
.imageScale(.small)
.accessibility(label: Text("Locate Me"))
.padding()
}
.background(Color.white)
.cornerRadius(10)
.padding()
}
}
}
}
А вот и MapView.swift:
import SwiftUI
import MapKit
import CoreLocation
import ECMapNavigationAble
struct MapView: UIViewRepresentable, ECMapNavigationAble{
var locationManager = CLLocationManager()
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
MKMapView()
}
func updateUIView(_ view: MKMapView, context: UIViewRepresentableContext<MapView>){
view.showsUserLocation = true
view.isPitchEnabled = false
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
if let userLocation = locationManager.location?.coordinate {
let userLocationEC = ECLocation(coordinate : userLocation, type: .wgs84)
let viewRegion = MKCoordinateRegion(center: userLocationEC.gcj02Coordinate, latitudinalMeters: 200, longitudinalMeters: 200)
view.userTrackingMode = .follow
view.setRegion(viewRegion, animated: true)
}
DispatchQueue.main.async{
self.locationManager.startUpdatingLocation()
}
}
}