imageswiftuikingfisher

Why doesn't SwiftUI's Kingfisher KFImage.Placeholder(UIImage(named: "logo")) accept UIImage as acceptable?


I add the following code to a VStack in SwiftUI:

KFImage.url(url)
     .placeholder(UIImage(named: "logo"))
     .setProcessor(processor)
     .loadDiskFileSynchronously()

But XCode doesn't like it and says "Cannot convert value of type UIImage? to expected argument type '() -> Content'"

Kingfisher's cheatsheet indicates that the placeholder line should work:

.placeholder(UIImage(named: "logo"))

When I remove the placeholder line (line2 above), it works properly. But, of course, there is no placeholder.

Using SwiftUI, how can I set the placeholder for KFImage?

I've only been coding with Swift/SwiftUI for a month now so I'm quite new.

Thankyou.

Swift Version 5.0 Kingfisher Version 6.1.0


Solution

  • The error that you are getting is telling that placeholder wants a SwiftUI View (eg () -> Content) and you're trying to provide it a UIKit UIImage instead.

    Instead, you should give it a SwiftUI Image.

    You could easily initialize Image with a UIImage, but keep in mind that UIImage(named:) returns an Optional (which your error hinted at as well), so if you want to use it without checking it for nil first, you'll need to force unwrap it:

    Image(uiImage: UIImage(named: "logo")!)
    

    Even better, just initialize your SwiftUI Image with the name and skip UIImage altogether unless you need it for some other reason:

    Image("logo")
    
    .placeholder { Image("logo") }