Check whether +[UIImage imageNamed:] found an image - objective-c

I have an long if statement to decide what image to show in a UIImageView. They are all .png files, and I use the code:
if (whatever) {
image = [UIImage imageNamed: #"imageName.png"];
}
Does anyone know of a way to check to see if the program can find the image? So that if the image does not exist in the program, it can display an error image or something?

+[UIImage imageNamed:]
will return nil if it couldn't find a corresponding image file. So just check for that:
UIImage *image = [UIImage imageNamed:#"foo.png"];
if (image == nil)
{
[self displayErrorMessage];
}

The shortest snippet would be
image = [UIImage imageNamed:#"imageName"] ? : [UIImage imageNamed:#"fallback_image"]
but do you really want such code?
Make another check:
if (whatever) {
image = [UIImage imageNamed: #"imageName.png"];
if(image == nil) {
image = [UIImage imageNamed: #"fallback_image"];
}
}
it still can be shorted, like
if(! (image = [UIImage imageNamed: #"imageName.png"]) ) {
...
}
but you're toying with readability here.

First, I'd suggest using a dictionary instead of a long if. You can key each image name by whatever. If whatever isn't currently an object, make an enum that will encapsulate that information and use NSNumbers to box the values of the enum.
Then, you can check for nil when you try to retrieve the image. imageNamed: uses nil to indicate failure, so:
if( !image ){
// No image found
}

Related

NSImage - can't load image from file

I program command-line application that will load image from Supporting Files. Image is copied in Supporting Files, but when I use following code, variable imgC returns nil.
NSString* pathC = #"galaxy.jpg";
NSImage* imgC = [NSImage imageNamed: pathC];
ImgC returns nil even if I use the following code:
NSString* pathC = #"galaxy.jpg";
NSImage* imgC = [[NSImage alloc] initWithContentsOfFile: pathC];
Can someone please help me?
(PS: Sorry for my bad English.)
Many thanks, Peter
Swift Style:
if let imageRef = NSImage(byReferencingFile: "/path/to/galaxy.jpg")
{
print("image size \(imageRef.size.width):\(imageRef.size.height)")
}
As the target is commend line tool since those don't have a bundle [NSBundle mainBundle] so its returns nil. So You need to used an absolute path, not an relative path. As this is Strange Xcode do't show any kind of warning regarding to this.
NSImage *image = [[NSImage alloc]initWithContentsOfFile:#"/Users/Zenga/Documents/iOS/Research/Test/star.png"];
if (image == nil) {
NSLog(#"image nil");
}
NSLog(#"%f and %f",image.size.width, image.size.height);
and i found this path from When i click on the Image and on Right Corner i found this path and i used it and working fine for me.

UISegmentedControll not setting correct image

I'm trying to set a custom image for each segment control index in my UISegmentedControll
I am setting the image like so:
UIImage *selectAll = [UIImage imageNamed:#"Select All Active"];
[selectAll imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[self.segmentedControl setImage:selectAll forSegmentAtIndex:0];
However I just get a white space in the segment index and the image doesn't show correctly.
Is there a different way to do this?
I am building the app for iOS7 only.
Edit
Here is what it looks like with image set in IB or Code:
Sounds like your image does not exists, are your sure it is named 'Select All Active.png'? I suggest you rename it to test.png first to see if it works.
I think Your UIImage object is nil So check is using.
UIImage *selectAll = [UIImage imageNamed:#"Select All Active"];
if (selectAll == nil) {
NSLog(#"nil");
}
If not nil you can try using
UIImage *selectAll;
if ([UIImage instancesRespondToSelector:#selector(imageWithRenderingMode:)]) {
selectAll = [[UIImage imageNamed:#"Select All Active"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}else {
selectAll = [UIImage imageNamed:#"Select All Active"];
}
self.segmentedControl.tintColor = [UIColor clearColor];
[self.segmentedControl setImage:selectAll forSegmentAtIndex:0];
I think what you are seeing is the divider of the UISegmentedControl. You need to set an image for the divider as well..

Having 2 UIimageviews load the same pic

I have 2 UIImageviews that I would like to share the same pic.png when the view controller loads. How do I link the UIImageviews to show the same pic?
It's simple
imageView1.image = [UIImage imageNamed:#"test.png"];
imageView2.image = imageView1.image;
Hope it helps you..
The most straightforward way is as follows:
self.imageView1.image = myImage;
self.imageView2.image = myImage;
If you want them linked so they always show the same image, you’re best off putting making a method like this. I’ve put the UIImageViews in an array, to show how you could expand this technique to as many image views as you want:
- (void)showImage:(UIImage *)newImage
{
for (UIImageView *imageView in imageViewsArray)
{
imageView.image = newImage;
}
}
Just set both UIImages to the same thing, or just give the second image the value of the first.
imageView.image = [UIImage imageNamed:#"Default.png"];
imageView2.image = imageView.image;

UITableViewCell Image not updating

I can update the detailTextLabel.text and the UITableViewCell shows the changes at runtime, but if I try to update the imageView.image it does not change the visible image. Any idea as to why? I have tried calling a refresh on the UITableViewCell specifically but to no avail.
-(void)getImageForURL:(NSURL*)url row:(UITableViewCell*)cell {
UIImage*image;
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url];
cell.imageView.image = image; // Does not work..
cell.detailTextLabel.text = #"test"; // Works
}
Try calling [cell setNeedsLayout] after setting the image, if it's the first image you're setting for the cell.
Make sure the cell style is UITableViewCellStyleDefault, because other cell types may always return nil imageView, instead of creating one on demand.
Check whether the image is nil or not. If its nil then the Image is not fetched from the URL correctly.
I too was having problems with adding the image to my imageView that was constrained in a tableview cell and was not updating with cell.setNeedsLayout(). Calling update methods on the tableview after the image was added did the trick for me:
cell.setNeedsLayout()
if #available(iOS 11.0, *) {
tableView.performBatchUpdates(nil, completion: nil)
}
else {
tableView.beginUpdates()
tableView.endUpdates()
}

UITableViewCell's imageView fit to 40x40

I use the same big images in a tableView and detailView.
Need to make imageView filled in 40x40 when an imags is showed in tableView, but stretched on a half of a screen. I played with several properties but have no positive result:
[cell.imageView setBounds:CGRectMake(0, 0, 50, 50)];
[cell.imageView setClipsToBounds:NO];
[cell.imageView setFrame:CGRectMake(0, 0, 50, 50)];
[cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
I am using SDK 3.0 with build in "Cell Objects in Predefined Styles".
I put Ben's code as an extension in my NS-Extensions file so that I can tell any image to make a thumbnail of itself, as in:
UIImage *bigImage = [UIImage imageNamed:#"yourImage.png"];
UIImage *thumb = [bigImage makeThumbnailOfSize:CGSizeMake(50,50)];
Here is .h file:
#interface UIImage (PhoenixMaster)
- (UIImage *) makeThumbnailOfSize:(CGSize)size;
#end
and then in the NS-Extensions.m file:
#implementation UIImage (PhoenixMaster)
- (UIImage *) makeThumbnailOfSize:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);
// draw scaled image into thumbnail context
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
// pop the context
UIGraphicsEndImageContext();
if(newThumbnail == nil)
NSLog(#"could not scale image");
return newThumbnail;
}
#end
I cache a thumbnail version since using large images scaled down on the fly uses too much memory.
Here's my thumbnail code:
- (UIImage *)thumbnailOfSize:(CGSize)size {
if( self.previewThumbnail )
return self.previewThumbnail; // returned cached thumbnail
UIGraphicsBeginImageContext(size);
// draw scaled image into thumbnail context
[self.preview drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
// pop the context
UIGraphicsEndImageContext();
if(newThumbnail == nil)
NSLog(#"could not scale image");
self.previewThumbnail = newThumbnail;
return self.previewThumbnail;
}
Just make sure you properly clear the cached thumbnail if you change your original image (self.preview in my case).
I have mine wrapped in a UIView and use this code:
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
(self is the wrapper UIView, with the dimensions I want - I use AsyncImageView).
I thought Ben Lachman's suggestion of generating thumbnails in advance rather than on the fly was smart, so I adapted his code so it could handle a whole array and to make it more portable (no hard-coded property names).
- (NSArray *)arrayOfThumbnailsOfSize:(CGSize)size fromArray:(NSArray*)original {
NSMutableArray *temp = [NSMutableArray arrayWithCapacity:[original count]];
for(UIImage *image in original){
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[temp addObject:thumb];
}
return [NSArray arrayWithArray:temp];
}
you might be able to use this?
yourTableViewController.rowImage = [UIImage imageNamed:#"yourImage.png"];
and/or
cell.image = yourTableViewController.rowImage;
and if your images are already 40x40 then you shouldn't have to worry about setting bounds and stuff... but, i'm also new to this, so, i wouldn't know, haven't played around with Table View row/cell images much
hope this helps.
I was able to make this work using interface builder and a tableviewcell. You can set the "Mode" properties for an image view to "Aspect Fit". I'm not sure how to do this programatically.
Try setting UIImageView.autoresizesSubviews and/or UIImageView.contentStretch.