1、Bundle 文件
-
Bundle 文件,簡單理解,就是資源文件包。我們將許多圖片、XIB、文本文件組織在一起,打包成一個 Bundle 文件。方便在其他項目中引用包內的資源。
-
Bundle 文件是靜態的,也就是說,我們包含到包中的資源文件作為一個資源包是不參加項目編譯的。也就意味着,bundle 包中不能包含可執行的文件。它僅僅是作為資源,被解析成為特定的 2 進制數據。
2、制作 Bundle 文件
-
1、新建 Bundle 項目
-
創建名為 SourcesBundle(最后要生成的 Bundle 文件名稱)的工程,注意 Bundle 默認是 macOS 系統的,Xcode 高版本中需要在 macOS => Framework & Library 選項下找到。
-
-
2、修改 Bundle 配置信息
-
因為 Bundle 默認是 macOS 系統的,所有需要修改他的信息,修改成 iOS 系統。
-
設置 Build Setting 中的
COMBINE_HIDPI_IMAGES
為 NO,否則 Bundle 中的圖片就是 tiff 格式了。
-
-
3、可選配置
-
作為資源包,僅僅需要編譯就好,無需安裝相關的配置,設置 Skip Install 為 YES。同樣要刪除安裝路徑 Installation Directory 的值。
-
該資源包的 pch 文件和 strings 文件是可以刪除的。
-
-
4、添加文件
-
將資源文件或文件夾拖動到工程中的 SourcesBundle 文件夾下面。
-
-
5、編譯生成 Bundle 文件
-
我們分別選擇 Generic iOS Device 和任意一個模擬器各編譯一次,編譯完后,我們會看到工程中 Products 文件夾下的 SourcesBundle.bundle 由紅色變成了黑色。
-
然后 show in finder,看看生成的文件。我們看到它為真機和模擬器都生成了 .bundle 資源文件。
-
選中 .bundle 文件右鍵 顯示包內容,我們可以看到之前拖拽到工程中的資源文件都在其中。
-
3、使用 Bundle 文件
-
將生成的真機(Debug-iphoneos)Bundle 資源文件拖拽到需要使用的工程中。
-
1、加載 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];
-
效果
-
-
2、加載 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];
-
效果
-