Bundle 文件,簡單理解,就是資源文件包。咱們將許多圖片、XIB、文本文件組織在一塊兒,打包成一個 Bundle 文件。方便在其餘項目中引用包內的資源。iphone
Bundle 文件是靜態的,也就是說,咱們包含到包中的資源文件做爲一個資源包是不參加項目編譯的。也就意味着,bundle 包中不能包含可執行的文件。它僅僅是做爲資源,被解析成爲特定的 2 進制數據。ui
一、新建 Bundle 項目3d
建立名爲 SourcesBundle(最後要生成的 Bundle 文件名稱)的工程,注意 Bundle 默認是 macOS 系統的,Xcode 高版本中須要在 macOS => Framework & Library 選項下找到。code
二、修改 Bundle 配置信息blog
由於 Bundle 默認是 macOS 系統的,全部須要修改他的信息,修改爲 iOS 系統。圖片
設置 Build Setting 中的 COMBINE_HIDPI_IMAGES
爲 NO,不然 Bundle 中的圖片就是 tiff 格式了。ip
三、可選配置資源
做爲資源包,僅僅須要編譯就好,無需安裝相關的配置,設置 Skip Install 爲 YES。一樣要刪除安裝路徑 Installation Directory 的值。string
該資源包的 pch 文件和 strings 文件是能夠刪除的。it
四、添加文件
將資源文件或文件夾拖動到工程中的 SourcesBundle 文件夾下面。
五、編譯生成 Bundle 文件
咱們分別選擇 Generic iOS Device 和任意一個模擬器各編譯一次,編譯完後,咱們會看到工程中 Products 文件夾下的 SourcesBundle.bundle 由紅色變成了黑色。
而後 show in finder,看看生成的文件。咱們看到它爲真機和模擬器都生成了 .bundle 資源文件。
選中 .bundle 文件右鍵 顯示包內容,咱們能夠看到以前拖拽到工程中的資源文件都在其中。
將生成的真機(Debug-iphoneos)Bundle 資源文件拖拽到須要使用的工程中。
一、加載 Bundle 中的 xib 資源文件
// 設置文件路徑 NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"SourcesBundle" ofType:@"bundle"]; NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath]; // 加載 nib 文件 UINib *nib = [UINib nibWithNibName:@"BundleDemo" bundle:resourceBundle]; NSArray *viewObjs = [nib instantiateWithOwner:nil options:nil]; // 獲取 xib 文件 UIView *view = viewObjs.lastObject; view.frame = CGRectMake(20, 50, self.view.bounds.size.width - 40, self.view.bounds.size.width - 40); [self.view addSubview:view];
效果
二、加載 Bundle 中的圖片資源文件
指定絕對路徑的形式
UIImage *image = [UIImage imageNamed:@"SourcesBundle.bundle/demo2.jpg"];
拼接路徑的形式
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"SourcesBundle" ofType:@"bundle"]; NSString *imgPath= [bundlePath stringByAppendingPathComponent:@"demo4"]; UIImage *image = [UIImage imageWithContentsOfFile:imgPath];
宏定義的形式
#define MYBUNDLE_NAME @"SourcesBundle.bundle" #define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:MYBUNDLE_NAME] #define MYBUNDLE [NSBundle bundleWithPath:MYBUNDLE_PATH] NSString *imgPath= [MYBUNDLE_PATH stringByAppendingPathComponent:@"demo4"]; UIImage *image = [UIImage imageWithContentsOfFile:imgPath];
效果