Rahul Sharma

Fix Image not showing in SwiftUI

The Problem

While working on my SwiftUI app, I had a weird issue while working with Image. In previous versions of Xcode 11 Beta, my app crashed on real device and simulator because it failed to find images in asset catalog when the images were in fact present in asset catalog. But, it worked fine in Live Preview.

In recent beta of Xcode 11, although it no longer causes crashes, it still fails to find images and doesn't shows Image at all.

The Fix

Surprisingly, Image created through UIImage worked! I used Image(uiImage:). This initializer takes in a UIImage.

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

UIImage is forcely unwrapped because I was sure the images are present in catalog.

This code looked kinda messy so I created an extension of Image.

extension Image {
    /// Use this initalizer if `Image` fails to find image
    /// - Parameter name: Image name in Asset Catalog
    init(named imageName: String) {
        self.init(uiImage: UIImage(named: name)!)

So now, I can just use it as Image(named: "imageName") and it now shows the image!

Tagged with: