이미지와 함께 SwiftUI에서 번들을 사용하는 방법

Aug 18 2020

예 : 프로젝트에 번들이 있습니다. "Game.Bundle"이라고합니다.

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

하지만 번들이 작동하지 않습니다.

커스텀 번들은 어떻게 사용하나요?

답변

1 Asperi Aug 18 2020 at 23:09

SwiftUI Image(_ , bundle: _)는 해당 번들의 자산 카탈로그에서 이미지 리소스를 찾습니다. 귀하의 경우 이미지는 일반 파일로 포함되어 있으므로 파일로 찾아서로드해야합니다. 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)
    }
}
1 WarrenBurton Aug 18 2020 at 22:42

제공된 스 니펫 은 인스턴스 및 지역 변수로 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
}