我想实现一个基本的地图视图,当用户点击按钮时,该视图将以用户位置为中心,类似于 Apple 地图应用程序。我尝试了以下操作,但每当我点击按钮时,[SwiftUI] Modifying state during view update, this will cause undefined behavior.都会在控制台中打印。在我看来,更新tracking状态变量导致了错误。但是,我不确定状态变量还有什么用途。尽管打印了错误,但应用程序确实按预期运行。有谁有这方面的经验或知道可能出了什么问题?
struct ContentView: View {
@State var region: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.3769, longitude: 8.5417), latitudinalMeters: 2000, longitudinalMeters: 2000)
@State var tracking = MapUserTrackingMode.follow
var body: some View {
ZStack {
Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking)
.ignoresSafeArea()
.task {
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization();
}
Button {
tracking = .follow
} label: {
Image(systemName: tracking == .follow ? "location.fill" : "location") …Run Code Online (Sandbox Code Playgroud)