简体   繁体   中英

How to Use Bundle In SwiftUI with Image

For example: i have Bundle in project, it is call "Game.Bundle"

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

but Bundle not work.

how can i use custom Bundle

在此处输入图像描述

Your snippet as provided seems to reference b both in self as an instance and as a local variable

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

Did you want?

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

Or refactored to eliminate force unwraps ! with some problem analysis added.

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
}

The SwiftUI Image(_, bundle: _) looks for image resource in corresponding bundle's Assets catalog. In your case the image is just embedded as regular file, so you have to find and load it as file. Image itself cannot do that, so it should be constructed with UIImage that has such possibility.

So, assuming you Game.bundle is in PlugIns subfolder of main bundle (if not - just correct corresponding path construction below) here is possible approach.

Tested with 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)
    }
}

You can use my extension:

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

In SwiftUI:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM