Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI No image named was found in main bundle

Tags:

ios

swiftui

I'm studying SwiftUI and have a problem with Image(name: String).

This is my ContentView

var body: some View {
    VStack {
        Image("test")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 75, alignment: .center)
            .clipped()
        List(retriever.items) { item in
            Row(coin: item)
        }
    }
}

When I ran this project, I got this message "Thread 1: Fatal error: No image named test was found in main bundle"

So, I tried below.

  • Image("test.jpg")
  • Image("images/test")
  • Image("images/test.jpg")

But, the result was same.

That image was in this path 'project root/images/test.jpg'


Strange thing is that this code works well.

Image(uiImage: UIImage(named: "test.jpg")!)

How can I solve this problem?

like image 886
Heejae Kim Avatar asked Jul 11 '19 15:07

Heejae Kim


5 Answers

You have to add your images to the Assets Catalog in your Xcode project structure so Apple can do some behind the scenes magic to prep them for use with multiple screen sizes. Double click your Assets.xcassets folder (make an assets folder if you don't have one) in your project pane on the left of your xcode editor, then drag and drop your image file into the catalog pane.

Calls like Image("your_image_name") should work after this.

like image 73
Cody Avatar answered Nov 18 '22 23:11

Cody


You should put your image to Assets.xcassets folder. Error message telling you literally - 'I can't find this image at Assets.xcassets'.

like image 25
Radagast Avatar answered Nov 18 '22 21:11

Radagast


Please check whether your imageset's Contents.json contains the same name of image name. Please see the below image.

ImageSet of Conference Room

This worked for me.

like image 1
Vinoth Vino Avatar answered Nov 18 '22 21:11

Vinoth Vino


I may be wrong but I think swift defaults to .png files. Perhaps when you simply write Image("test") it is looking for "test.png"

Try saving your image as a .png, placing it in the assests folder, and using Image("test") like you have been using above.

like image 1
joe Avatar answered Nov 18 '22 23:11

joe


Came across this thread from Google. None of the answers worked for me. I had dropped that PNG file into the project and this worked:

if let image_url = Bundle.main.url(forResource: "selfie", withExtension: "png") {
    Image(uiImage: UIImage(imageLiteralResourceName: image_url.lastPathComponent)!)
        .renderingMode(.original)
        .resizable().scaledToFit()
}

I had to use the overloaded version of Image(uiImage: UIImage(imageLiteralResourceName:)). Just specify the file name of that image only, using absolute path of the image file won't work

like image 1
Asesh Avatar answered Nov 18 '22 22:11

Asesh