我们做项目的时候,可能会将项目中其中一个小模块抽出来,分装成一个framework使用,里面不仅会有.h、.m文件,可能还会有xib以及图片音频等资源。
现在我们做一下这方面的教程。
1、首先,我们创建一个Framework的项目,选择Framework & Library里面的Cocoa Touch Framework。项目名就叫:Dog。

2、我们在Dog项目中导入一个Animals的实体文件夹,里面还有controllers、views、models3个实体文件,这一步主要用于模拟现实项目中的文件所在的复杂路径。

3、加载xib文件。
在controllers文件夹中新建文件DogViewController(包含xib文件),并在xib文件中加入一个标题为“小狗的叫声是”的button,并实现其点击事件。

然后再新建一个DogVoiceViewController(不带xib)以及DogVoiceView(带xib)文件。

重点:
我们要在DogVoiceViewController中显示DogVoiceView的xib文件中的东西。
因为我们最终会形成framework的形式,让别的应用使用,所以不能使用[NSBundle mainBundle]来获取xib的路径,要使用[NSBundle bundleForClass:[DogVoiceView class]]获取xib的路径。如图:

最后,我们让点击“小狗叫声是”按钮的时候跳转到DogVoiceViewController页面。

4、加载资源文件。
我们再新建一个存放图片的Bundle,command+N,选择Resource里面的settings Bundle。命名为images.Bundle。

新建成功之后,我们将Bundle里面的默认文件和文件夹都删除。然后添加一张图片进行备用。

我们在DogViewController.xib文件中载入一个UIImageView,用于显示图片。
注意:图片也需要特殊的bundle路径。如图:
图片名称要用相对路径:images.bundle/IMG_0165

5、设置公开的.h文件
在Dog.h文件中添加需要公开的文件头部。

在TARGETS -> Build Phases -> Headers 将DogViewController.h从Project移到Public中。

最后运行Dog项目获得Dog.framework文件。(注意,在真机上运行的到的dog.framework文件只能在真机上使用;在模拟器运行的文件只能在模拟器上使用;如果想要同时在真机和模拟器上使用的话,需要合并真机和模拟器的Dog.framework文件。)

测试Dog.framework是否可用:
1、创建测试项目DogTest。
2、将Dog.framework文件引入DogTest工程。
3、在DogTest工程的Targets -> General -> Embedded Binaries 引入framework。

4、在Build Phases -> Copy Bundle Resources 引入framework.

5、调用framework里面的文件。
应用头文件:#import<Dog/Dog.h>
调用framework里面的xib文件时,需要特定的bundle路径。如图:

运行结果:


OK,Framework的创建以及其中xib文件和图片资源的引用就到这里了,再见!
网友评论