ios - 如何在带有图像的 SwiftUI 中使用 Bundle

标签 ios swift swiftui

例如: 我在项目中有 Bundle,它叫做“Game.Bundle”

let b :Bundle = Bundle.init(path: Bundle.main.path(forResource:"Game", ofType:"bundle")!)!
Image("Giyuu",bundle:self.b)

但 Bundle 不起作用。

我如何使用自定义 Bundle

enter image description here

最佳答案

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/

相关文章:

ios - 在 Mac 上运行的 ios 应用程序上,getPlatformName() 会返回什么?

ios - 多个获取请求?

ios - 将 UIStackView 与具有动态高度的 UITextView 结合使用

ios - 在 SwiftUI 中实现外部显示器支持

swiftui - 是否可以使用绑定(bind)设置 SwiftUI DatePicker minimumDate?

ios - 在代码生成的 UIView 上绘制 UIBezierPath

ios - 如何在 CloudKit 记录中搜索部分单词?

ios - CrashReporter,缺少必需的体系结构x86_64

ios - 快速创建单独的计时器

ios - 仅将 SidebarListStyle() 应用于 Mac