这是那些会让你彻底发疯的错误之一,直到你接受它的含义正是它所说的: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 的 SwiftUI 教程 https://developer.apple.com/tutorials/swiftui如果你还没有,然后Paul Hegarty 的 CS193p 课程 https://cs193p.sites.stanford.edu真正感受它是如何运作的。