如何开发一个包含图像资源的iOS框架?

7

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

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

然后我建立了一个演示来测试我的框架,但发现crossImage和arrowImage都是null;之后,我发现imageNamed:方法会在应用程序的目录中搜索图像而不是框架的目录,所以我可以通过将这两个图像添加到演示项目中来修复它。但是,这几乎不是优雅的解决方案。有没有其他的解决方案来定位我的框架中的图像?

5个回答

23

你可以使用以下方式从框架中加载图像:

+ (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 上该怎么办呢? - Grey
1
据我所知,在iOS 7和6.0中,苹果不支持创建自定义框架。为此,请使用静态库和自定义bundle。 - Midhun MP

1
这只有在你的图片不在.xcasserts文件夹中才有效。
UIImage *image = [UIImage imageNamed:@"YourFramework.framework/imageName"]

1
最后,我创建了一个捆绑包来保存所有图像资源,我们提供 *.framework 和 *.bundle,更加优雅。

3
您能否更清楚地说明您是如何提供这些的?提供一些示例代码会很有帮助。 - Herbal7ea

1

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

[[UIImage alloc] initWithContentsOfFile:path];

你需要从捆绑路径生成的路径。类似于:
NSBundle *bundle = [NSBundle bundleForClass:[YourFramework class]];
NSString* path = [bundle pathForResource:@"cross.jpg" ofType:nil];

0

我成功地通过使用Swift框架加载了我的图像

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接