例如: 我在项目中有 Bundle,它叫做“Game.Bundle”
let b :Bundle = Bundle.init(path: Bundle.main.path(forResource:"Game", ofType:"bundle")!)!
Image("Giyuu",bundle:self.b)
但 Bundle 不起作用。
我如何使用自定义 Bundle
最佳答案
SwiftUI Image(_ , bundle: _)
在相应的 bundle 的 Assets 目录中查找图像资源。在您的情况下,图像只是作为常规文件嵌入,因此您必须将其作为文件查找并加载。 Image
本身不能做到这一点,因此应该使用具有这种可能性的 UIImage
来构造它。
因此,假设您的 Game.bundle
位于主包的 PlugIns
子文件夹中(如果不是 - 只需更正下面的相应路径构造),这是可能的方法。
使用 Xcode 12/iOS 14 测试
struct ContentView: View {
var body: some View {
Image(uiImage: gameImage(name: "test") ?? UIImage())
}
func gameImage(name: String, type: String = "png") -> UIImage? {
guard let plugins = Bundle.main.builtInPlugInsPath,
let bundle = Bundle(url: URL(fileURLWithPath:
plugins).appendingPathComponent("Game.bundle")),
let path = bundle.path(forResource: name, ofType: type)
else { return nil }
return UIImage(contentsOfFile: path)
}
}
关于ios - 如何在带有图像的 SwiftUI 中使用 Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63470030/