iOS_Bundle资源文件包

Bundle文件

  • Bundle 文件,简单理解,就是资源文件包。我们将许多图片、XIB、文本文件组织在一起,打包成一个 Bundle 文件。方便在其他项目中引用包内的资源。
  • Bundle 文件是静态的,也就是说,我们包含到包中的资源文件作为一个资源包是不参加项目编译的。也就意味着,bundle 包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的 2 进制数据。

制作Bundle文件

  1. 新建Bundle项目
新建项目.png

2.修改 Bundle 配置信息


01.png
  • 设置 Build Setting 中的 COMBINE_HIDPI_IMAGES 为 NO,否则 Bundle 中的图片就是 tiff 格式了。


    02.png
  • 作为资源包,仅仅需要编译就好,无需安装相关的配置,设置 Skip Install 为 YES。同样要删除安装路径 Installation Directory 的值。


    03.png

    04.png
  • 设置完成后,将需要添加的资源copy到项目中,
    分别选择Generic iOS Device 和 iPhone模拟器运行一遍,然后在Show in Finder中找到编译出的真机Bundle就可以用了。


    05.png
06.png

使用示例代码如下:

 // 设置文件路径
    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];

原文链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、Bundle 文件 Bundle 文件,简单理解,就是资源文件包。我们将许多图片、XIB、文本文件组织在一起,...
    Coder_Long阅读 14,445评论 3 9
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,173评论 25 709
  • 框架捆绑 框架是封装动态共享库和支持该库所需的资源文件的分层目录。框架比典型的动态共享库提供了一些优势,因为它们为...
    nicedayCoco阅读 5,581评论 0 2
  • 介绍 捆绑是macOS和iOS中用于封装代码和资源的基础技术。软件包通过为所需资源提供已知位置来简化开发人员体验,...
    nicedayCoco阅读 5,030评论 0 1
  • 1听说是很简单的编辑器 1.1.测试下 好的,不错 1听说是很简单的编辑器 1.1.测试下 好的,不错
    叫我IM阅读 818评论 0 1