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?
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.
You should put your image to Assets.xcassets folder. Error message telling you literally - 'I can't find this image at Assets.xcassets'.
Please check whether your imageset's Contents.json
contains the same name of image name. Please see the below image.
This worked for me.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With