我有一个项目使用了iOS 14中的新SwiftUI地图
我希望能够动态更新地图中心的位置。
当您点击缩放按钮,然后点击位置按钮,地图工作正常,并重新居中到伦敦。
然而,如果你只是点击位置按钮,它会重新定位到伦敦,但会抛出一个关于ViewState的警告。
我不知道是什么导致了这个问题,也不知道如何解决它。
struct ContentView: View {
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 25.7617,
longitude: 80.1918
),
span: MKCoordinateSpan(
latitudeDelta: 10,
longitudeDelta: 10
)
)
var body: some View {
VStack {
Map(coordinateRegion: $region)
Button("zoom") {
withAnimation {
region.span = MKCoordinateSpan(
latitudeDelta: 100,
longitudeDelta: 100
)
}
}
Button(action: {
withAnimation {
region = MKCoordinateRegion(center: CLLocationCoordinate2D(
latitude: 51.507222,
longitude: -0.1275),
span: MKCoordinateSpan(
latitudeDelta: 0.5,
longitudeDelta: 0.5))
}
}) {
Image(systemName: "location.fill")
.frame(width: 44, height: 44, alignment: .center)
.foregroundColor(.black)
.background(Color(.white))
}
.buttonStyle(PlainButtonStyle())
.clipShape(Circle())
.shadow(color: .black.opacity(0.5), radius: 1.0, x: 0.0, y: 2.0)
}
}
}发布于 2021-07-14 09:31:22
这是其中一个错误,它会让您完全抓狂,直到您接受它的意思与它所说的完全相同:runtime: SwiftUI: Modifying state during view update, this will cause undefined behavior.按钮在视图中,当您按下它时,您正在更新视图并试图修改它。解决方案是让这种修改过的数据来自视图结构之外。
我创建了一个类来保存地图坐标:
import Foundation
import MapKit
class Coordinates: ObservableObject {
public static let shared = Coordinates()
@Published var region: MKCoordinateRegion
init() {
self.region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 25.7617,
longitude: 80.1918
),
span: MKCoordinateSpan(
latitudeDelta: 10,
longitudeDelta: 10
)
)
}
}然后我修改了ContentView以接受数据:
struct ContentView: View {
@ObservedObject var coordinates = Coordinates.shared
var body: some View {
VStack {
Map(coordinateRegion: $coordinates.region)
Button("zoom") {
withAnimation {
coordinates.region.span = MKCoordinateSpan(
latitudeDelta: 100,
longitudeDelta: 100
)
}
}
Button(action: {
withAnimation {
coordinates.region = MKCoordinateRegion(center: CLLocationCoordinate2D(
latitude: 51.507222,
longitude: -0.1275),
span: MKCoordinateSpan(
latitudeDelta: 0.5,
longitudeDelta: 0.5))
}
}) {
Image(systemName: "location.fill")
.frame(width: 44, height: 44, alignment: .center)
.foregroundColor(.black)
.background(Color(.white))
}
.buttonStyle(PlainButtonStyle())
.clipShape(Circle())
.shadow(color: .black.opacity(0.5), radius: 1.0, x: 0.0, y: 2.0)
}
}
}您并不一定要这样做,但您需要记住构建SwiftUI所依据的MVVM原则,并将您的真理源与您的视图分开。如果你还没有,我会运行Apple's SwiftUI tutorials,然后运行Paul Hegarty's CS193p class来真正了解它是如何工作的。
https://stackoverflow.com/questions/68365989
复制相似问题