iosswiftui

SwiftUI No image named was found in main bundle


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.

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?


Solution

  • 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.