我最近为我的 Swift 项目制作了一个 Mapview,问题是地图没有以用户的位置为中心,只有我必须按两次的 Button 才能使地图以用户为中心。 该代码还获得了用户位置,我怀疑这与代码在抽签前没有获得位置有关,但我还没有找到一种方法来实现它。 (抱歉,如果这可能是一个简单的解决方案,我对 Swift 和 SwiftUI 比较陌生)
这是 MapView 的代码:
import SwiftUI
import MapKit
import CoreLocation
let locationManager = CLLocationManager()
struct MapView: View {
@State private var locationService = Location()
@State private var userTrackingMode: MapUserTrackingMode = .follow
@State var region = MKCoordinateRegion(center: MapDetails.defaultCenter, span: MapDetails.defaultSpan)
var body: some View {
ZStack{
if(AppInfo.LocationIsEnabled){
Map(
coordinateRegion: $region,
interactionModes: MapInteractionModes.all,
showsUserLocation: true,
userTrackingMode: $userTrackingMode
)
Button {
withAnimation{
userTrackingMode = MapUserTrackingMode.follow}
}
label: {
if (userTrackingMode == MapUserTrackingMode.none){
Image(systemName: "location")
.padding(10)
.foregroundColor(.white)
}
else{
Image(systemName: "location.fill")
.padding(10)
.foregroundColor(.white)
}
}
.background(.black.gradient)
.cornerRadius(8, antialiased: /*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/)
.frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .topTrailing)
.shadow(radius: 5, x: 1, y: 1)
.padding(10)
}
else
{
Text("Location Services Disabled")
}
}
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
enum MapDetails {
static let defaultCenter = CLLocationCoordinate2D(latitude: 48.0823, longitude: 11.3357)
static let defaultSpan = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
}
final class Location: NSObject, ObservableObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?
func initialize() {
checkLocationAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager = CLLocationManager()
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.delegate = self
print("Location Enabled")
}
else{
print("Show an alert")
}
print("Location Initialized")
}
private func checkLocationAuthorization(){
guard let locationManager = locationManager else {return}
switch locationManager.authorizationStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
AppInfo.LocationIsEnabled = false
print("Location is Restricted")
case .denied:
AppInfo.LocationIsEnabled = false
print("Location is Denied")
case .authorizedAlways, .authorizedWhenInUse:
AppInfo.LocationIsEnabled = true
MapView().region = MKCoordinateRegion(center: locationManager.location!.coordinate, span: MapDetails.defaultSpan)
@unknown default:
AppInfo.LocationIsEnabled = false
break
}
print("LocationService Checked", AppInfo.LocationIsEnabled)
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
}
我试过在Mapdraw之前调用location Initializer,但是好像不行……