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];
效果