从框架加载xib文件



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

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

如果我的客户端应用程序正在使用情节串连板,我该如何加载此视图?注意,我确实设法访问了提到的控制器上的属性,所以我做了苹果文档和其他地方描述的所有连接等。

提前感谢!

您必须将资源放在*.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}"
    

最新更新