在我們使用第三方架構時,常常看到XXX.bundle的檔案。
我們找到該檔案,顯示包内容,大緻看到很多資源檔案:圖檔、配置文本、XIB檔案……
什麼是Bundle檔案?
簡單了解,就是資源檔案包。我們将許多圖檔、XIB、文本檔案組織在一起,打包成一個Bundle檔案。友善在其他項目中引用包内的資源。
Bundle檔案的特點?
Bundle是靜态的,也就是說,我們包含到包中的資源檔案作為一個資源包是不參加項目編譯的。也就意味着,bundle包中不能包含可執行的檔案。它僅僅是作為資源,被解析成為特定的2進制資料。
制作Bundle
1.建立bundle項目
2.添加需要的圖檔
加入你需要編譯在bundle中的資源檔案。
當然,預設的配置也是可以的,如果你需要特定的優化或者特定的路徑配置,你可以進行下面第3步的配置。
3.你可以對編譯的bundle進行一些可選的設定(可選)
a.作為資源包,僅僅需要編譯就好,無需安裝相關的配置。
b.同樣要删除安裝路徑。
c.該資源包的pch檔案和strings檔案是可以删除的。
4.最好狀态下,要編譯出适用與iPhone的bundle檔案。
項目內建bundle
使用bundle就非常的easy了,将編譯好的XXXX.bundle 檔案直接加入到需要的項目中。省略了!
使用bundle中的資源
将要使用的bundle內建到項目中後,就可以使用了。需要注意的就是,bundle是靜态的,不進行編譯的資源檔案。是以,要使用bundle中的資源,就需要找到相應的資源路徑。
這裡廢話就不多說了,貼代碼!
VC獲得bundle中的資源
NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @ "MyBundle"ofType :@ "bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name"bundle:resourceBundle];
圖檔獲得bundle中的資源
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50,50)];
UIImage *image = [UIImage imageNamed:@"MyBundle.bundle/img_collect_success"];
[imgView setImage:image];
或者
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50,50)];
NSString *imgPath= [bundlePath stringByAppendingPathComponent:@"img_collect_success.png"];
UIImage *image_1=[UIImage imageWithContentsOfFile:imgPath];
[imgView setImage:image_1];
當然,可以寫成預編譯語句:
#define MYBUNDLE_NAME @ "MyBundle.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]