如何在Swift 3中加载自定义捆绑包

7
在 Objective-C 中,我正在做这个:
NSString *path = [[NSBundle mainBundle] pathForResource:@"LUIImages" ofType:@"bundle"];
path = [[NSBundle bundleWithPath:path] pathForResource:_imageHash ofType:nil];

但我似乎找不到在Swift 3中的等价物

let bundlePath: String = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")!

但是接下来该怎么办呢?或者有更好的方法来加载自定义包吗?


Bundle(path: "...")?.path(forResource: "...", ofType: "...")?- 尝试使用自动补全,它应该会指导你。 - Martin R
哈,我已经使用了init,但这个方法显然也可以……你想把它变成一个答案,这样我就可以确认它吗? - Ondrej Rafaj
1个回答

25

使用Bundle(path:)构造函数,避免强制解包:

if let bundlePath = Bundle.main.path(forResource: "LiveUI", ofType: "bundle"),
    let bundle = Bundle(path: bundlePath),
    let path = bundle.path(forResource: "...", ofType: nil) {
    print(path)
} else {
    print("not found")
}

另一种方法是使用捆绑包标识符(在捆绑包的 Info.plist 中定义)来加载捆绑包:

let bundle = Bundle(identifier: "com.company.bundle.LiveUI")

3
我们该如何在plist中注册自定义bundle? - Chirag Lukhi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接