【发布时间】:2021-08-02 18:22:10
【问题描述】:
我在将 ObservedObject 与 SwiftUI 一起使用时遇到问题。我的应用有两个主要视图:
- 第一个视图称为 MapView,其中包含一个带有不同注释的地图。
- 第二个视图称为 MapSettingsView,有一个 DatePicker 和一个用于类别的 Picker,我可以在其中决定 MapView 中哪些注释可见,哪些不可见。
每个注释都有特定的属性,例如日期、类别和坐标(纬度、经度)。 每个注释都保存在我的 Firebase 实时数据库中,因此为了获取它们,我构建了一个 API,它可以调用我想要的所有信息,效果很好。
在 MapSettingsView 中选择了我想要的所有属性后,我有一个按钮,它在我的 FirebaseTasks 类中调用一个函数 (loadPublicLocations)。然后,此函数根据 Firebase 中的这些属性调用所有位置。这也很有效,因为我打印了所有想要的位置。为了根据新的位置数组刷新 MapView,FirebaseTasks 中的所有位置都附加到 @Published var publicLocations = [LocationModel]()。在 MapView 内部,注释基于这个数组,我通过 @ObservedObject 属性获得。
现在的问题是:在 FirebaseTasks 中,所有想要的位置都附加到“publicLocations”数组中。 MapView 不会刷新,虽然注解是基于 ObservedObject taskModel.publicLocations。
地图视图:
struct MapView: View {
@ObservedObject var taskModel = FirebaseTasks()
@State var showSettings = false
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 25.7617,
longitude: 80.1918
),
span: MKCoordinateSpan(
latitudeDelta: 10,
longitudeDelta: 10
)
)
var body: some View {
VStack {
HStack {
Button(action: {
showSettings.toggle()
}) {
Image(systemName: "line.horizontal.3.decrease")
.font(.title)
.foregroundColor(.black)
}
.sheet(isPresented: $showSettings) {
MapSettings(mapViewModel: MapSettingsViewModel("all", category: "all", lat: 21, long: 21))
}
}
.padding(.horizontal)
.padding(.top)
.padding(.bottom,10)
Map(coordinateRegion: $region, annotationItems: taskModel.publicLocations, annotationContent: { (location) -> MapMarker in
MapMarker(coordinate: CLLocationCoordinate2D(latitude: location.lat!, longitude: location.long!), tint: .red) // does not get data on refreshed MapSettings
})
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
}
}
}
Firebase 任务:
class FirebaseTasks: ObservableObject {
// Model
@Published var publicLocations = [LocationModel]() {
didSet {
print(publicLocations) // works
}
}
// Location related
func loadPublicLocations(category: String, date: String, currentLat: Double, currentLong: Double) {
publicLocations.removeAll()
PublicLocationApi.system.addPublicRadiusLocationObserver(category, date: date, currentLat: currentLat, currentLong: currentLong) { (location) in
print(location) // works
self.publicLocations.append(location)
}
}
}
【问题讨论】:
-
在我稍微简化了这段代码以便我可以运行它之后,它非常适合我。问题可能在于您未显示的代码,例如
LocationModel。
标签: ios swift firebase swiftui mapkit