[英]How to Use Bundle In SwiftUI with Image
您提供的代碼段似乎在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.