我試圖從 struct gService 獲取經度和緯度并將其設定在地圖上。但無法初始化@State var region,因為錯誤“不能在屬性初始化程式中使用實體成員'服務';屬性初始化程式在'self'可用之前運行”service.latitude和service.longitude
struct DetailCardView: View {
let service: gService
@State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
var body: some View {
Map(coordinateRegion: $region, annotationItems: [MapPoint(coordinates: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude))]) { location in
MapAnnotation(coordinate: location.coordinates) {
Circle()
.stroke(.red, lineWidth: 3)
.frame(width: 50, height: 50, alignment: .center)
}
}
我用谷歌搜索了這個問題,但有不同的情況。
uj5u.com熱心網友回復:
基本上,編譯器所說的是“我仍在創建你的實體DetailCardView,我還不知道它的價值是什么,service所以我不能在region”中使用它。
解決方案是將 傳遞service給將用于初始化這兩個屬性的常量。您需要為傳遞此常量的 View 創建一個初始化程式。
這是它的外觀:
let service: gService
// Rather than service.longitude and service.latitude, use a dummy value, like 0.0
// Recommended this var to be private
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
// Here's your initializer
init(service: gService) {
self.service = service // Use service to initialise self.service
// Use service - and NOT self.service - to initialise region
region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
}
var body: some View {
... // The rest of your code
您可以嘗試的另一種方法是洗掉init()并設定region視圖何時出現,如下所示:
let service: gService
// Rather than service.longitude and service.latitude, use a dummy value, like 0.0
// Recommended this var to be private
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
var body: some View {
Map(coordinateRegion: $region, annotationItems: [MapPoint(coordinates: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude))]) { location in
MapAnnotation(coordinate: location.coordinates) {
Circle()
.stroke(.red, lineWidth: 3)
.frame(width: 50, height: 50, alignment: .center)
}
.onAppear {
region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: service.latitude, longitude: service.longitude), span: MKCoordinateSpan(latitudeDelta: 0.0033, longitudeDelta: 0.0033))
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429699.html
下一篇:如何從父母委托給多個不同的孩子?
