【问题标题】:How to develop an iOS framework which includes image resources?如何开发包含图片资源的 iOS 框架?
【发布时间】:2015-04-30 21:49:46
【问题描述】:

我正在开发一个包含图像资源的iOS框架,我在框架中调用以下方法,

crossImage = [UIImage imageNamed:@"cross"];
arrowImage = [UIImage imageNamed:@"arrow"];

然后我构建了一个demo来测试我的框架,但是发现crossImage和arrowImage都是nil;之后,我发现imageNamed:method 将在应用程序目录而不是框架目录中搜索图像,因此我可以通过将两个图像添加到演示项目来修复它。然而,它几乎不优雅。那么还有其他针对我的框架中的图像的解决方案吗?

【问题讨论】:

    标签: ios objective-c frameworks nsbundle ios-frameworks


    【解决方案1】:

    您可以使用以下方法从框架加载图像:

    + (UIImage *)imageNamed:(NSString *)name
                   inBundle:(NSBundle *)bundle
    compatibleWithTraitCollection:(UITraitCollection *)traitCollection
    

    方法。

    在你的框架类中这样写:

    NSBundle *frameWorkBundle = [NSBundle bundleForClass:[self class]];
    UIImage *arrow = [UIImage imageNamed:@"arrow" inBundle:frameWorkBundle compatibleWithTraitCollection:nil];
    UIImage *cross = [UIImage imageNamed:@"cross" inBundle:frameWorkBundle compatibleWithTraitCollection:nil];
    

    有关此方法的更多信息,请参阅UIImage Class Reference

    【讨论】:

    • 你建议的方法只支持iOS 8.0及更高版本,如果是iOS 7.0和6.0呢?
    • @GaojinHsu:iOS 7 和 6.0 苹果中的 AFAIK 不支持创建自定义框架。为此目的使用静态库和自定义包
    【解决方案2】:

    您还可以使用以下方式加载图像:

    [[UIImage alloc] initWithContentsOfFile:path];
    

    您要从包路径生成的路径。比如:

    NSBundle *bundle = [NSBundle bundleForClass:[YourFramework class]];
    NSString* path = [bundle pathForResource:@"cross.jpg" ofType:nil];
    

    【讨论】:

      【解决方案3】:

      最后,我创建了一个bundle来存放所有的图片资源,我们提供了*.framework和*.bunlde,这样更优雅。

      【讨论】:

      • 您能否更清楚地说明您是如何提供这些内容的?示例代码会很有帮助。
      【解决方案4】:

      这仅在您的图片不在.xcasserts 中时有效。

      UIImage *image = [UIImage imageNamed:@"YourFramework.framework/imageName"]
      

      【讨论】:

        【解决方案5】:

        我设法通过使用将我的图像加载到 Swift 框架中

        UIImage(named: name, in: Bundle.module, compatibleWith: nil)
        

        【讨论】:

          猜你喜欢
          • 2015-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多