Hello, I had a lab session earlier today to try and handle an issue with images getting dumped in SwiftUI and always seeing the placeholder image instead of the loaded image. The engineer recommended @StateObject as a replacement for @ObservedObject in the AsyncImage but Im getting an error.
Is there a recommended way to use this new feature of SwiftUI for Async Images?
With @StateObject in place of @ObservedObject 'loader' below throws error "Cannot assign to property: 'loader' is a get-only property"
Thanks!
Is there a recommended way to use this new feature of SwiftUI for Async Images?
With @StateObject in place of @ObservedObject 'loader' below throws error "Cannot assign to property: 'loader' is a get-only property"
Code Block struct AsyncImage<Placeholder: View>: View { @ObservedObject private var loader: ImageLoader private let placeholder: Placeholder? init(url: URL, placeholder: Placeholder? = nil) { loader = ImageLoader(url: url) self.placeholder = placeholder } var body: some View { image .onAppear(perform: loader.load) .onDisappear(perform: loader.cancel) } private var image: some View { Group { if loader.image != nil { Image(uiImage: loader.image!) .resizable() .aspectRatio(contentMode: .fit) } else { Image("Placeholder") .resizable() .aspectRatio(contentMode: .fit) } } } }
Thanks!
I'm afraid you do not understand what I say.
You need to initialize loader at the place of declaration.
Writing this way is mandatory.
Also, you need to check if your ImageLoader has an initializer with no arguments -- init(). Explicitly defined or implicitly generated.
You need to initialize loader at the place of declaration.
Writing this way is mandatory.
Code Block @StateObject private var loader = ImageLoader() //<- You need this here.
Also, you need to check if your ImageLoader has an initializer with no arguments -- init(). Explicitly defined or implicitly generated.