如何在 Swift 3 中加载自定义包
How do I load a custom bundle in Swift 3
在 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:)
构造函数并避免强制展开:
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")
在 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:)
构造函数并避免强制展开:
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")