【发布时间】:2022-10-02 00:19:20
【问题描述】:
我正在使用下面的代码来执行以下操作。
- 每 5 秒创建一个新项目并将其附加到模型
- 在 listView 中显示项目列表
- 在mapView中显示项目的地图
如果我在 listView 中,列表会每 5 秒正确更新一次新项目。没有错误信息。 如果我在 mapView 中,地图也会更新(每 5 秒一个新标记),但我收到错误“[SwiftUI] 不允许从视图更新中发布更改,这将导致未定义的行为。\” 由于 list 和 map 都显示相同的模型数据,我想知道为什么 map 抱怨而 list 没有。实际的模型更新在主角身上,所以它为什么抱怨。
任何想法?
//Model struct TestApp1Model { struct TestItem: Identifiable { var id = UUID() var name: String var latitude: Double var longitude: Double } var items = [TestItem]() } // ViewModel class TestApp1ViewModel: ObservableObject { @Published private var model = TestApp1Model() private var timer:Timer? init() { timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in Task { @MainActor in self.addItem() } } } var items:[TestApp1Model.TestItem] { model.items } @MainActor func addItem () { let name = \"Item \" + model.items.count.description let latitude = Double.random(in: 45...55) let longitude = Double.random(in: 5...11) model.items.append(TestApp1Model.TestItem(name: name, latitude: latitude, longitude: longitude)) } } // View struct TestApp1View: View { @StateObject var testVM = TestApp1ViewModel() @State var region:MKCoordinateRegion init() { self.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 50, longitude: 8), span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 6)) } var body: some View { TabView { listView .tabItem { Image(systemName: \"list.bullet\") Text(\"List\") } .backgroundStyle(Color.white) mapView .tabItem { Image(systemName: \"map\") Text(\"Map\") } .backgroundStyle(Color.white) } } var listView: some View { VStack { List (testVM.items) { item in HStack { Text(item.name) Text(item.latitude.description) Text(item.longitude.description) } } } } var mapView: some View { Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true,annotationItems: testVM.items) {item in MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: item.latitude, longitude: item.longitude)) { Image(systemName: \"plus\") .foregroundColor(.red) } } .ignoresSafeArea() } }
标签: swift swiftui mapkit publish-subscribe xcode14