封裝SDK等組件時(shí),為了不在宿主項(xiàng)目中額外配置資源文件,通常將SDK所用資源文件打成.bundle文件。
創(chuàng)建Bundle
1.選中工程目錄。點(diǎn)擊添加Target
- 選擇macOS,搜索
bundle,選擇Bundle,下一步。 -
設(shè)置bundle名字
- 選中bundle的Target,在Build settings 下搜索
combine, 將COMBINE_HIDPI_IMAGES值改為No。(不然打包成bundle中的圖片會(huì)編程.tiff格式) -
新建一個(gè)分組,用來裝需要打包的資源文件
將資源文件放入Bundle
-
將外部的資源文件拖入文件夾內(nèi),并選擇Target為創(chuàng)建的Bundle
-
將資源文件導(dǎo)入后的結(jié)構(gòu)
生成.bundle文件
-
選中Bundel工程,編譯。
-
點(diǎn)擊Product中Show Build Folder in Finder
-
在Debug內(nèi)有生成的.bundle文件
-
顯示包內(nèi)容,可以檢查一下生成的bundle文件中是否包含所需資源文件
使用.bundle
-
沒問題了就可以將.bundle文件拖入項(xiàng)目中。這次用的Target是宿主,所以選擇宿主Target。
- 使用
2.1 OC
@interface UIImage (BundleImage)
+ (UIImage *)loadBundleImage:(NSString *)imageName;
@end
@implementation UIImage (BundleImage)
+ (UIImage *)loadBundleImage:(NSString *)imageName {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"TestAppBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
return [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];
}
@end
調(diào)用:
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 18, 18)];
img.image = [UIImage loadBundleImage:@"arrowLeft"];
[self.view addSubview:img];
2.2 Swift
class ChatbotBundle {
static func getZKSmartBundle() -> Bundle {
if let bundleURL = Bundle.main.url(forResource: "ChatbotBundle", withExtension: "bundle"),
let bundle = Bundle(url: bundleURL) {
return bundle
} else {
fatalError("ZKSmart.bundle not found.")
}
}
}
extension UIImage {
static func loadBundleImage(_ name: String) -> UIImage {
return UIImage(named: name, in: ChatbotBundle.getZKSmartBundle(), compatibleWith: nil)!
}
}
調(diào)用:
lazy var backBtn: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .clear
button.setImage(UIImage.loadBundleImage("arrowLeft"), for: .normal)
return button
}()










