how to add xib file in static library in iOS

2020-07-11 05:01发布

I am trying to add xib file or any other view controller file within static library but I can't do so. Can you please help me?

If possible please add the whole source code

their is button on first view. And when clicking on that button, new view controllers comes up with something (lets say changes in background color). How to create static library for this? so that I may use it in another project?

Thanks in advance

3条回答
放荡不羁爱自由
2楼-- · 2020-07-11 05:45

Strictly speaking, it's correct that you cannot add a Xib to a static library. However, there are workarounds. Matt Galloway's iOS Library With Resources tutorial will show you how to do just that.

See iOS Library With Resources.

查看更多
三岁会撩人
3楼-- · 2020-07-11 05:47

If you want to build your interfaces using interface builder when building a static library you will need to make a bundle and distribute it with your library.

In Xcode:

  1. File> New> Target
  2. Select "Bundle" from the OS X Framework and Library section
  3. Fill in the details. The bundle framework should be core foundation.

Then you need to get your bundle compiled at the same time as your framework. Add the bundle to the "Target Dependencies" build phase of your framework.

When you make your xibs you make their target this new bundle you have created.

Then when you compile your framework in the derived data directory, next to your framework binary you will find your compiled bundle. You give this to your third parties along with the framework binary.

So how do you reference this bundle in your code? In iOS bundles cant be loaded and your bundle will actually be inside the third party's iOS application main bundle. You can create a category on NSBundle for conveniently accessing your bundle from your code:

@interface NSBundle (mybundle)
+(NSBundle *)myBundle;
@end

@implementation NSBundle (mybundle)

static NSBundle * _myBundle;

+(NSBundle *)myBundle{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        NSBundle * mainBundle = [NSBundle mainBundle];
        NSString * pathToMyBundle = [mainBundle pathForResource:@"myBundle" ofType:@"bundle"];

        NSAssert(pathToMyBundle, @"bundle not found", nil);

        _myBundle = [NSBundle bundleWithPath:pathToMyBundle];
    });

    return _myBundle;
}

You can then access your bundle in code to load xibs like this:

UIViewController * controller = [[UIViewController alloc] initWithNibName:nil bundle:[NSBundle myBundle]];

Remember that if you use categories in your framework code you will need to make sure that your framework consumers add the -ObjC (or -all_load if not using a recent Xcode) "other linker flag" to their projects

查看更多
来,给爷笑一个
4楼-- · 2020-07-11 05:58

XIB is like resource and what static library is , a compiled file that contains ur classes. You can say it is your compiled code ready to be used. You can not add xib's to static library.

查看更多
登录 后发表回答