Issue #626
SwiftUI does not trigger onAppear and onDisappear like we expect. We can use NSView to trigger
import SwiftUI
struct AppearAware: NSViewRepresentable {
var onAppear: () -> Void
func makeNSView(context: NSViewRepresentableContext<AppearAware>) -> AwareView {
let view = AwareView()
view.onAppear = onAppear
return view
}
func updateNSView(_ nsView: AwareView, context: NSViewRepresentableContext<AppearAware>) {
}
}
final class AwareView: NSView {
private var trigged: Bool = false
var onAppear: () -> Void = {}
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
guard !trigged else { return }
trigged = true
onAppear()
}
}
Then we can use it as an hidden view, like in a ZStack
ZStack {
AppearAware(onAppear: {
LocalImageCache.shared.load(url: url) { image in
self.image = image
}
})
Image(image)
}