2018-05-24 自定义bundle 放置xib文件

参考文章
1.NSInternalInconsistencyException - Could not load NIB in bundle:
2.iOS Library With Resources
3.Git Resource

The other day I was finding myself wondering why it was so complicated to create a “framework” for iOS which contained XIBs, graphics, etc. People are using techniques such as iOS Universal Framework which I tried but had problems with setting a breakpoint in the framework project. I thought there must be a better way to do it when I thought about the idea of having a simple static library and a resources bundle. It worked! And in this tutorial I show how you can do it for yourself.

If you want to just skip to download the sample project then please do so, or carry on reading for a full description of what to do.

Step 1: Create the library project

First of all you need to create a library project which will be a standard Cocoa Touch static library first of all. So go ahead and create a new project from the “Cocoa Touch Static Library” template as shown in the following two screenshots.


image.png

image.png

Step 2: Adding a copy files phase

In order for the headers from the static library to be picked up by a project which includes it, we need to add a copy files phase to the library to copy the headers to a certain directory. From a bit of trial and error and some other blog posts I found that we need to put these into the “Products Directory” under a subpath of include.

To add the phase you need to go to the build settings of the library project and under the “Build Phases” tab you’ll see a button called “Add Build Phase”. Click that and set it up as per the screenshots below.


image.png

image.png

Step 3: Adding the resources bundle target

The magic for getting the resources to play nicely is to put all the resources into a bundle which we’ll include from another project. So we need to add a target to the library project of type “Bundle”. From the build settings of your library project click the “Add Target” button and use the screenshot below to help you set it up.


image.png

Step 4: Fixing the resources bundle target

When the resources bundle target is added, it will default to being set up with a Mac OS X build target. This is wrong because we want an iOS one so you just need to change the relevant settings to whatever you want your iOS target to be (probably “Latest iOS”). Use the screenshot below to guide you in doing this.


image.png

Step 5: Adding a XIB to the bundle target

In order to get resources to be put into the bundle all you have to do is add them to the “Copy Bundle Resources” build phase of the target. The following screenshot shows an example of MyViewController.xib being put into the bundle.

image.png

Step 6: Creating the app project

Now we’re ready to create an app which will use the library. So let’s go ahead and do that. Just create an empty application for now. The following screenshots show an example of doing that.


image.png

image.png

Step 7: Linking with the library

In order to get the static library to be linked with the main app project you just need to drag the library project from Finder into the navigator pane in Xcode and drop it next to the project. It doesn’t really matter if it’s a sub project or a sibling project in a workspace – do whichever you feel most comfortable with.

Then we need to edit the app’s scheme to make it build the library project’s targets first. So edit the scheme and under the “Build” tab click the plus at the bottom and add the library target and library resources target. You should then have something which looks like the following screenshot.


image.png

Step 8: Linking against the library

We now need to tell the app project to link against the static library from the library project. To do this you just need to add it to the list of linked frameworks in the target. The following screenshot shows an example of doing this.


image.png

We also need to add the bundle from the library project to the main app project. To do this we just need to drag it across from the navigator pane to the “Copy Bundle Resources” phase of the application project. Once done it should look something like the following screenshot.


image.png

Step 9: Final setup of app project

The last bit to do is to set up the header search paths of the app project. Go to the build settings of the app project and look for “User Header Search Paths”. Then set the target setting to $(BUILT_PRODUCTS_DIR) so that it looks something like the following screenshot.

image.png

After you’ve done that you’re ready to go! The finished project should look something like the following screenshot in the navigator pane.


image.png

Step 10: Coding the example view controller

In my example I created a view controller called MyViewController with a XIB that gets put into the library bundle. The code for this just has to be a bit different to normal to pick up the XIB from our library bundle. So here is the code:

#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController

@end

@implementation MyViewController

- (id)init {
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"MyLibraryResources" withExtension:@"bundle"]];
    if ((self = [super initWithNibName:@"MyViewController" bundle:bundle])) {
    }
    return self;
}

@end

The only difference here is that we’re picking the XIB from the MyLibraryResources bundle that is built in the library project. It really is as simple as that. Graphics which are included in that bundle will be immediately accessible from the XIBs included in the library bundle as well.

Here’s an example screenshot just to show it really does work:


image.png

Download sample project.

Extras

I found it useful to add a category on NSBundle which enables me to access the library bundle without having to type a lot of code each time. So something like this would suffice:

@interface NSBundle (MyLibrary)
+ (NSBundle*)myLibraryResourcesBundle;
@end

@implementation NSBundle (MyLibrary)

+ (NSBundle*)myLibraryResourcesBundle {
    static dispatch_once_t onceToken;
    static NSBundle *myLibraryResourcesBundle = nil;
    dispatch_once(&onceToken, ^{
        myLibraryResourcesBundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"MyLibraryResources" withExtension:@"bundle"]];
    });
    return myLibraryResourcesBundle;
}

@end

Then you can change the code in your view controller initialisers to be:

if ((self = [super initWithNibName:@"MyViewController" bundle:[NSBundle myLibraryResourcesBundle]])) {
}

Another useful trick is to have a category on UIImage so that loading images from the bundle is easy. I use something like the following which first looks for the image using the normal imageNamed: method and if that fails then it looks it up in the resources bundle. This is useful because then the app can override graphics as it wishes.

@implementation UIImage (MyLibrary)
+ (UIImage*)myLibraryImageNamed:(NSString*)name;
@end

@implementation UIImage (MyLibrary)

+ (UIImage*)myLibraryImageNamed:(NSString*)name {
    UIImage *imageFromMainBundle = [UIImage imageNamed:name];
    if (imageFromMainBundle) {
        return imageFromMainBundle;
    }

    UIImage *imageFromMyLibraryBundle = [UIImage imageWithContentsOfFile:[[[NSBundle myLibraryResourcesBundle] resourcePath] stringByAppendingPathComponent:name]];
    return imageFromMyLibraryBundle;
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容