我在 Xcode 15 中有一个 Swift Playground,其文件结构如下:
|-.swiftpm/
|----Resources/
| |----cat.png
| |----plane.png
| |----train.png
|----MyApp.swift
|----ExampleView.swift
在
ExampleView.swift
中,我有Xcode(使用“+”按钮)来帮助我插入图像:
import SwiftUI
struct ExampleView: View {
var body: some View {
Image("cat.png")
}
}
但是预览时图像不显示,我也尝试过:
Image(uiImage: #imageLiteral(resourceName: "cat.png"))
和
Image(uiImage: UIImage(named: "cat.png")!)
正如 How can I use image inside Xcode 11 Playground? 和 How do we show an image in a SwiftUI Playground? 的答案中所建议的那样 但是,它们在预览期间都崩溃了,并且删除
.png
扩展也不起作用。原来我在添加图片文件的时候,添加到了“Resources”文件夹下,并没有起作用。将其添加到根文件夹进行第二次尝试,Xcode在项目中创建了
Assets.xcassets
,并且成功了。