Reputation: 49788
I'm debugging a problem with an imageView not being shown.
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
NSLog(@"imageView right after initialization is: %@", imageView);
imageView.frame = CGRectMake(2, 0, 316, 45);
imageView.layer.zPosition = zPos;
NSLog(@"imageView after running the setters: %@", imageView);
[self.view addSubview:imageView];
The weird part is that sometimes the imageView
gets displayed, sometimes it's not (about 75% of the time it's displayed).
imageView
is not accessed anywhere except the code above.
What I noticed is that when the imageView
is not displayed, the first log statement shows that:
imageView right after initialization is: <UIImageView: 0x9eaa760; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x9ec04a0>>
When the image view is displayed:
imageView right after initialization is: <UIImageView: 0xaa61ad0; frame = (0 0; 644 88); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xaa61330&rt;&rt;
EDITED: I ran tens of tests, the imageView always behaves the same: when it is not shown, the initial frame is (0 0; 0 0). When it's not, it's always some other value.
P.S. I'm not using ARC.
Upvotes: 4
Views: 546
Reputation: 23558
In addition to rckoenes answer you must always check if the image exists within your bundle path first:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory
= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:imageName];
if([fileManager fileExistsAtPath:path])
{
UIImage *image = [UIImage imageNamed:imageName];
if (!image) {
NSLog(@"Image could not be found: %@", imageName);
}
imageView = [[UIImageView alloc] initWithImage:image];
} else {
NSLog(@"%@ is not included in the app file bundle!", imageName);
}
that way you'll know if the problem is b/c you don't have the file in the first place.. or b/c there is something wrong with file that prevents iOS from loading it.
Upvotes: 1
Reputation: 69499
In your log of the UIImageView
it show frame = (0 0; 0 0);
This means that the view will not be shown since it has a height and width of 0. Which indicates that the image has no size or is nil
.
The cause of this is most probably because the image your are trying to load is not found: You should check wether the image is found or not:
UIImage *image = [UIImage imageNamed:imageName];
if (!image) {
NSLog(@"Image could not be found: %@", imageName);
}
imageView = [[UIImageView alloc] initWithImage:image];
Meaning that even if you change the frame you will still see nothing since there is no image loaded.
Upvotes: 2
Reputation: 5498
Why don't you set the frame first and set the image next?
imageView = [UIImageView alloc]initWithFrame:CGRectMake(0,0,35,35)];
[imageView setImage:[UIImage imageNamed:@"img.png"]];
Upvotes: 2