7

I am developing an iOS framework which includes image resources, I call the methods below in the framwork,

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

and then I build a demo to test my framework, but find crossImage and arrowImage are both nil; Afterwards, I figure out imageNamed:method will search images in the app's directory not in the framework's, so I can fix it by adding the two images to the demo project. However, it's barely elegant. so any other solutions to target the images in my framework?

Vineet Choudhary
  • 7,433
  • 4
  • 45
  • 72
Grey
  • 253
  • 4
  • 15

5 Answers5

23

You can load the image from framework using:

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

method.

In your framework class write like:

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

Refer UIImage Class Reference for more info about this method.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • The method you suggest only supports iOS 8.0 and later, what if on iOS 7.0 and 6.0? – Grey Mar 04 '15 at 08:09
  • 1
    @GaojinHsu: AFAIK in iOS 7 and 6.0 apple won't support creating custom frameworks. Use Static Library and custom bundle for this purpose – Midhun MP Mar 04 '15 at 08:13
1

You can also load images using:

[[UIImage alloc] initWithContentsOfFile:path];

The path you'll want to generate from the bundle path. Something like:

NSBundle *bundle = [NSBundle bundleForClass:[YourFramework class]];
NSString* path = [bundle pathForResource:@"cross.jpg" ofType:nil];
DanielG
  • 2,237
  • 1
  • 19
  • 19
1

This will work only when your images is NOT in .xcasserts.

UIImage *image = [UIImage imageNamed:@"YourFramework.framework/imageName"]
Ved Rauniyar
  • 1,539
  • 14
  • 21
Nix Wang
  • 814
  • 10
  • 18
1

At last, I create a bundle to hold all image resources, and we provide *.framework and *.bunlde, that's more elegant.

Grey
  • 253
  • 4
  • 15
0

I managed to load my images in a Swift framework by using

UIImage(named: name, in: Bundle.module, compatibleWith: nil)
villapossu
  • 2,737
  • 4
  • 18
  • 19