Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create UIImageView from file

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?

like image 791
Tneuktippa Avatar asked Nov 23 '25 04:11

Tneuktippa


2 Answers

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).

like image 196
benzado Avatar answered Nov 24 '25 19:11

benzado


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"]];
like image 21
Obliquely Avatar answered Nov 24 '25 19:11

Obliquely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!