簡體   English   中英

如何使用 Bundle In SwiftUI with Image

[英]How to Use Bundle In SwiftUI with Image

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

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

但捆綁包不起作用。

我怎樣才能使用自定義包

在此處輸入圖像描述

您提供的代碼段似乎在self中將b作為實例和局部變量引用

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)

或者重構以消除 force unwraps ! 添加了一些問題分析。

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: _)在相應的 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM