
什么是Bundle文件?
简单理解,就是资源文件包。我们将许多图片、XIB、文本文件组织在一起,打包成一个Bundle文件。方便在其他项目中引用包内的资源。

Bundle文件的特点?
Bundle是静态的,也就是说,我们包含到包中的资源文件作为一个资源包是不参加项目编译的。也就意味着,bundle包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的2进制数据。

项目集成bundle
使用bundle就非常的easy了,将编译好的XXXX.bundle 文件直接加入到需要的项目中。(拖进去就👌)省略了!

使用bundle中的资源
将要使用的bundle集成到项目中后,就可以使用了。需要注意的就是,bundle是静态的,不进行编译的资源文件。所以,要使用bundle中的资源,就需要找到相应的资源路径。
VC获得bundle中的资源
<pre>
NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @ "MyBundle"ofType :@ "bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name"bundle:resourceBundle];
</pre>
图片获得bundle中的资源
<pre>
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIImage *image = [UIImageimageNamed:@"MyBundle.bundle/img_collect_success"];
[imgView setImage:image];
</pre>
或者
<pre>
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];
</pre>
当然,可以写成预编译语句:
<pre>
define MYBUNDLE_NAME @ "MyBundle.bundle"
define MYBUNDLE_PATH [[[NSBundlemainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
define MYBUNDLE[NSBundle bundleWithPath: MYBUNDLE_PATH]
</pre>
网友评论