微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在SwiftUI和图片中使用捆绑包

如何解决如何在SwiftUI和图片中使用捆绑包

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

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

但捆绑包不起作用。

我如何使用自定义捆绑包

enter image description here

解决方法

您提供的摘录似乎在b中引用了self作为实例和局部变量

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

你想要吗?

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

或通过重构以消除强制解开!,并添加了一些问题分析。

func getGiyuuImage() -> Image {
    guard let path = Bundle.main.path(forResource:"Game",ofType:"bundle"),let bundle = Bundle(path: path) else {
        fatalError("dev error - no Game bundle")
    }
    let image = Image("Giyuu",bundle: bundle)
    return image
}
,

SwiftUI Image(_,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)
    }
}
,

您可以使用我的扩展程序:

extension Image {
    init(path: String) {
        self.init(uiImage: UIImage(named: path)!)
    }
}

在 SwiftUI 中:

Image(path: "Game.bundle/Giyuu.png")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。