SwiftUI:当不可见的 Core Data 属性更改时更新视图

问题描述 投票:0回答:1

我有一个 SwiftUI 视图,在其中显示图像,该图像取自 MapKit 的 MKMapSnapshotter,该图像依赖于从 Core Data 属性派生的一些信息(即标记的坐标和颜色)。我希望能够在任何信息发生变化时重新生成图像。我不知道如何实现这一点。这并不像对我想要观察的 NSManagedObject 使用

@ObservedObject
那么简单,因为可以更改的属性在 SwiftUI 视图上不直接可见,该视图仅显示图像。

我尝试在某些核心数据属性上使用

onChange
,但它不会触发(可能是因为这些属性在 SwiftUI 视图上实际上不可见)。还有其他解决办法吗?

struct CJContactProfileAddressLabelTestView: View {
    
    @ObservedObject var personAddress: PersonAddress
    @ObservedObject private var locationManager: ContactProfileLocationManager // generates an image using MKMapSnapshotter
    
    init(personAddress: PersonAddress) {
        self.personAddress = personAddress
        self.locationManager = ContactProfileLocationManager(personAddress: personAddress)
    }
    
    var body: some View {
        
        VStack {
            
            if let addressString = personAddress.addressStringWithoutCountry() {
                Text("\(addressString)").multilineTextAlignment(.leading)
            }
            
            if let mapImage = locationManager.mapImage {
                
                Image(uiImage: mapImage)
                    .resizable()
                    .cornerRadius(10)
            }
        }
        .task {
            print("CJProfileAddressView: task called")
            await self.locationManager.getMapSnapshot(from: CLLocation(latitude: self.personAddress.latitude as! CLLocationDegrees, longitude: self.personAddress.longitude as! CLLocationDegrees))
        }
    }
}
swiftui core-data
1个回答
0
投票

通常

mapImage
是一个瞬态属性:

https://developer.apple.com/documentation/coredata/modeling_data/configuring_attributes

此外,

.task
是为您调用异步函数而设计的,该函数返回您在
@State
上设置的结果,因此不需要对象。

© www.soinside.com 2019 - 2024. All rights reserved.