我需要在一个静态库中包含图片。 我创建了一个bundle并将图片插入其中,问题是如果我直接把图片放在bundle中似乎是可以工作的,但如果放在xcassets文件中就会停止工作。
我遵循了许多指南并在这个网站上搜索解决方案。最受欢迎的解决方案是插入这行代码:
[UIImage imageNamed:@"MyBundle.bundle/imageName"]
但似乎对我不起作用
有什么想法吗?
我需要在一个静态库中包含图片。 我创建了一个bundle并将图片插入其中,问题是如果我直接把图片放在bundle中似乎是可以工作的,但如果放在xcassets文件中就会停止工作。
我遵循了许多指南并在这个网站上搜索解决方案。最受欢迎的解决方案是插入这行代码:
[UIImage imageNamed:@"MyBundle.bundle/imageName"]
但似乎对我不起作用
有什么想法吗?
有两种解决方法,
如果你的应用程序仍支持iOs 7,你可以使用这个类别: https://gist.github.com/serluca/e4f6a47ffbc19fccc63e
否则,从iOs 8开始,苹果公司提供了一种使用以下方式实现此功能的方法:
+ imageNamed:inBundle:compatibleWithTraitCollection:
定义在 这里
遇到了相同的问题。看起来1-parameter imageNamed方法中XCAssets的inline bundle支持已经损坏了。不过,有一个解决办法可以使用imageNamed:inBundle:compatibleWithTraitCollection:。请注意,这只适用于iOS8!!
NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"static_lib_bundle_name" ofType:@"bundle"]];
UIImage *image = [UIImage imageNamed:@"image_in_the_xcassets_you_want" inBundle:bundle compatibleWithTraitCollection:nil];
注意:根据苹果文档,traitCollection设置为nil,以传递主屏幕特征(如果有人知道这是什么意思,请留言!)。
对于Swift 2.1:
let bundle = pathToBundle // define for your app or framework
if let image = UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil) {
// process image
}
NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"image.jpg" inBundle:bundle compatibleWithTraitCollection:nil];