Reputation: 1898
I have added an image (jpg) from my Photo Album to the UserResources folder (via the + menu in the upper right of the Playground app). How do I reference that file when declaring a SwiftUI Image?
I have tried using the entire path:
let path: String = { Bundle.main.paths(forResourcesOfType: "JPG", inDirectory: nil)[0] }()
It seems to give me the path to the desired file, “PICT0024.JPG”:
/var/mobile/Containers/Data/PluginKitPlugin/F01FA67E-97CA-4590-915A-C8071507C6E0/Library/Application Support/Main Module Resources Bundles/55929C8C-46C9-4691-B86B-389D1473E9A8.bundle/Contents/Resources/PICT0024.JPG
I then declare:
Image(systemName: path)
But the image is not shown. I probably have the wrong reference, but cannot figure out what I need to specify.
Oh, just this
Image(“PICT0024.JPG”)
doesn’t work either.
What is the proper way to reference that image file?
Please confine answers to SwiftUI 5 and editing on an iPad. Using XCode at the moment isn’t an option.
Thanks.
Upvotes: 6
Views: 8355
Reputation: 522
import SwiftUI
import PlaygroundSupport
// Add image to the project with the "+" button,
// then select either the file, or image icon,
// then navigate to desired image,
// then add it to the iPad Playground project
let imageFileNameString = "IMG_2702.jpeg"
struct ContentView: View {
var body: some View {
// the method below requires the UIImage be unwrapped
Image(uiImage: UIImage(named: imageFileNameString)!)
// -or-
// The commented-out method below does not require any unwrapping.
// Typos will fail with "something went wrong around here" error
// Image(uiImage: UIImage(imageLiteralResourceName: imageFileNameString))
.resizable()
}
}
PlaygroundPage.current.setLiveView( ContentView() )
Upvotes: 1
Reputation: 27
This is what I used: https://www.appcoda.com/swiftui-swift-playgrounds-ipad-mac/
[Edit by original poster] Summarizing from the article (worth a read because it discusses far more than how to access an image resource), here’s how to do it:
Image.
and using the autocomplete bar, pick the moon and mountains icon (ImageLiteral)The result looks like this:
[The image here is of buttercups, Ranunculus acris.]
Upvotes: 0
Reputation: 258541
Image(systemName: path)
this constructor one is for system SF Symbols
Image(“PICT0024.JPG”)
this constructor is for images in Assets catalog
The external images you have to use like this
Image(uiImage: UIImage(contentsOfFile: path))
Upvotes: 10