3

I have an image of a checkmark as a .png in the same directory as my project, called "checkbox.png". I want to create a UIImageView with that image as the background and set it as the accessory view of a set of UITableViewCells. I currently have:

UIView * v = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:@"checkmark.png"]];
v.backgroundColor = [UIColor redColor];
cell.accessoryView = v;
[v autorelease];

Which isn't working. I can make another dummy UIView (ex.

v = [[UIView alloc] init]; 
v.backgroundColor = [UIColor redColor];

which works fine, it displays a little red box on the right side of my uitableviewcells. I"m not sure why the view with the checkbox isn't working. Is there something wrong with the way I'm specifying the path to the file?

Tneuktippa
  • 1,645
  • 3
  • 15
  • 25

3 Answers3

7

imageWithContentsOfFile: requires the path to the file. If you just give it a file name, it will look for the file in the current directory, but to be honest I have no clue what the current directory usually is in an iOS app, or even if there are any guarantees.

The point is, you either need to give it the absolute path to the file or use imageNamed: which just takes a name and looks in the main bundle's resources.

In other words:

UIImage *image = [UIImage imageNamed:@"checkmark"];
UIView *view = [[UIImageView alloc] initWithImage:image];

Another advantage of imageNamed: is that it will cache the image (in case you use it again) and it will automatically look for a checkmark@2x version if your device has a Retina display.

If you do not want this behavior, you can get the path directly:

NSString *imagePath = [[NSBundle mainBundle] pathForResourceNamed:@"checkmark" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

This is usually a better option if it's a large image and you don't want to cache it (because you won't be using it very often).

benzado
  • 82,288
  • 22
  • 110
  • 138
1

You need to have the file path if you use the imageWithContentsOfFile: method. If the image is in your main bundle then the following will do the trick:

 UIView * v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmark.png"]];
Obliquely
  • 7,002
  • 2
  • 32
  • 51
1

Make sure you have added the image file to your XCode project. It's not enough to just have it in the same directory. From within XCode, select the File menu, then "Add Files to..." your project.

LandedGently
  • 693
  • 1
  • 8
  • 16