iOS Bundle的生成和使用
hi,勇敢的小夥伴兒們大家好,昨天一位朋友問我如何處理專案裡的圖片,是放在Assets.xcassets嗎,我說是啊,
他問~
“你會打包成Bundle嗎?”
“啊?我不會。”
“不會學啊,愣著幹嘛?”
“噢,抽時間吧。”
於是這篇文章在這個午休期間應運而生。
以下正文:
什麼是Bundle檔案?
簡單理解,就是資原始檔包。我們將許多圖片、XIB、文字檔案組織在一起,打包成一個Bundle檔案。方便在其他專案中引用包內的資源。
Bundle檔案的特點?
Bundle是靜態的,也就是說,我們包含到包中的資原始檔作為一個資源包是不參加專案編譯的。也就意味著,bundle包中不能包含可執行的檔案。它僅僅是作為資源,被解析成為特定的2進位制資料。1.新建一個工程macOS的Bundle專案
2.命名
3.刪除資料夾和info.plist檔案
4.刪除Build Settings裡的Packaging的info.plist的檔案地址
5.設定Base SDK為iOS
6.新增要打包的資原始檔進到資料夾
7.我添加了一張圖片
8.編譯,然後找到下圖的按鈕開啟資料夾
9.找到Bundle檔案,右鍵顯示包內容,檢視是否將資原始檔加入其中
10.檢查無誤之後,將Bundle拷貝到iOS專案中
11.開始使用
這是一種方法,還有其他方法。
NSString * bundlePath = [[ NSBundle mainBundle] pathForResource
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name"bundle:resourceBundle];
或者UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50,50)];
NSString *imgPath= [bundlePath stringByAppendingPathComponent
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]