Impossible to load an image in xcassets on bundle

2019-02-09 06:07发布

I need to include images in a static library. I created a bundle and inserted in my images, the problem is that it seems to work if I include the images directly in the bundle, but stops working if I put in a xcassets file.

I followed many guides and searched for a solution on this site. The most popular solution is to insert this line of code:

[UIImage imageNamed:@"MyBundle.bundle/imageName"] 

but it seems not work for me

any ideas?

4条回答
放荡不羁爱自由
2楼-- · 2019-02-09 06:15

Running the same problem. Looks like inline bundle support is broken for XCAssets in the 1-parameter imageNamed method. There's a workaround though using imageNamed:inBundle:compatibleWithTraitCollection: Be careful, this is iOS8 only !!

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];

NOTE : traitCollection is set to nil to pass the main screen traits as per apple docs (i don't quite get what it means though, if anyone knows please comment!).

查看更多
甜甜的少女心
3楼-- · 2019-02-09 06:15

For 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
}
查看更多
倾城 Initia
4楼-- · 2019-02-09 06:17

There are two ways to solve this,

If your app is still supporting iOs 7, you can use this category: https://gist.github.com/serluca/e4f6a47ffbc19fccc63e

Otherwise, starting from iOs 8 Apple added a way to do this using: + imageNamed:inBundle:compatibleWithTraitCollection: defined here

查看更多
闹够了就滚
5楼-- · 2019-02-09 06:33

Our images are placed in Images.xcassets and we had a problem with loading images in an IBDesignable. The following code did the job for the preview in Interface builder and the app as well:

NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"image.jpg" inBundle:bundle compatibleWithTraitCollection:nil];
查看更多
登录 后发表回答