从框架加载 xib 文件

Load xib file from framework

我正在创建一些代码,并将其分类到一个框架中 - 纯粹是因为我想在其他地方重用这些代码(其他 osx 应用程序 - 而不是 iOS)。

在我的 Resources 文件夹中,我创建了一个 xib 文件。在我的根目录中更高一层,我有相应的控制器文件。

如果我的客户端应用程序使用故事板 - 我将如何加载此视图?请注意,我确实设法访问了上述控制器上的属性,因此我按照 Apple 文档和其他地方的描述进行了所有连接等操作。

提前致谢!

您必须将资源放在 *.bundle 中,而不是框架中。 只需创建一个捆绑的新目标。

然后加载笔尖:

NSString *resourceBundlePath = [[NSBundle mainBundle] pathForResource:@"myBundle" ofType:@"bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:resourceBundlePath];

// load View Controller from that
UIViewController *vc = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:resourceBundle];

解决方案: 下面是加载xib在框架中创建视图的示例:

  1. 创建一个新包(例如:MyBundle.bundle)并将您的所有资源(例如:xib、图像、音频文件等)放入新包中。
  2. 加载 xib:

    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString* path = [resourcePath 
    stringByAppendingPathComponent:@"MyBundle.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if(bundle)
    {
        self.view = [[bundle loadNibNamed:@"MyXibNameWithoutSuffix" owner:nil options:nil] lastObject];
    } else {
        self.view = [[[NSBundle mainBundle] 
    loadNibNamed:@"MyXibNameWithoutSuffix" owner:nil options:nil] lastObject];
    }
    
  3. 加载图片:

    UIImage* image = [UIImage imageNamed:@"MyBundle.bundle/MyImageName"];
    if(nil == image) {
       image = [UIImage imageNamed:@"MyImageName"];
    }
    
  4. 如果您使用的是 cocopods,请确保 s.resources 在 .podspec 文件中设置。

    s.resources = "MyBundle.bundle/**/*.{png,jpeg,jpg,storyboard,xib,xcassets,plist}"