I have a Swift Playground in Xcode 15 that has a file structure as follows:
|-.swiftpm/
|----Resources/
| |----cat.png
| |----plane.png
| |----train.png
|----MyApp.swift
|----ExampleView.swift
In ExampleView.swift
, I had Xcode (using "+" button) to help me insert the Image:
import SwiftUI
struct ExampleView: View {
var body: some View {
Image("cat.png")
}
}
But the image would not show on preview, I also tried:
Image(uiImage: #imageLiteral(resourceName: "cat.png"))
and
Image(uiImage: UIImage(named: "cat.png")!)
As suggested in the answer of How can I use image inside Xcode 11 playground? and How do we display an image in a SwiftUI playground?
However, both of them crashed during preview and removing .png
extension does not work either.
What can I do next?
It turns out that when I was adding the image file, I added it under the folder "Resources" and didn't work. Added it to the root folder for the second try, Xcode created Assets.xcassets
in the project, and it worked.