I have a VStack of views where each view contains an ArtworkView:
struct ArtworkView: View {
let artworkId: UInt64
@State private var uiImage: UIImage?
@Environment(\.scenePhase) var scenePhase
@ViewBuilder var imageView: some View {
if let uiImage = uiImage {
Image(uiImage: uiImage)
}
else {
Image(systemName: "photo").opacity(0.4)
}
}
var body: some View {
imageView
.onAppear() {
loadArtwork(withId: artworkId) {
uiImage = $0
}
}
.onChange(of: scenePhase) { scenePhase in
if scenePhase == .background {
uiImage = nil
}
}
}
}
At first sight it works as expected – images appear on launch and disappear upon transition to the background.
But when I profile with Instruments > Allocations there is no difference in memory usage between foreground and background. And I need images to be unloaded from memory in background.
Does SwiftUI VStack or Image cache underlying UIImage objects and if so, how to opt out of it?