Reputation: 6342
I'm playing around with imageView and there is the method [ imageWithContentsOfFile]; But actually it doesn't show anything after run it. Below the code , there is the [ imageNamed:] method and it works as usual. Any ideas? Thanks,
#import "ViewController2.h"
@interface ViewController2 ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController2
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// just fugly don't do it
// self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"stanford"]];
UIBarButtonItem *shareItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];
UIBarButtonItem *cameraItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];
NSArray *actionButtonItems = @[shareItem, cameraItem];
self.navigationItem.rightBarButtonItems = actionButtonItems;
NSString *imgPath =[[NSBundle mainBundle] pathForResource:@"google" ofType:@"png"];
self.imageView.image = [UIImage imageWithContentsOfFile:imgPath];
// self.imageView.image = [UIImage imageNamed:@"google"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
I guess the problem is pathForResource method doesn't work properly somehow...
Upvotes: 3
Views: 2207
Reputation: 13323
If you're targeting iOS 7+, and using Asset Catalogs (which it looks like you're using, since you specified images.xcassets in one of your comments), Xcode 5 now puts the assets into a new file format. 1 file for all of the assets. This means you can not get access to the file directly using imageWithContentsOfFile:
. And that's also why pathForResource:ofType:
doesn't return a path.
If you need to access the file directly, you can include it as an normal image outside of an asset catalog.
You should also ask yourself if you need to access the file directly. In most cases you can use imageNamed:
. Which also gives you automatic caching for the image and can improve performance.
Upvotes: 4
Reputation: 10424
-- > Right click on the image in project Navigator
-- > Show in finder
-- > Right click on the image in finder
-- > Get info
-- > Look for file name and extension.
-- > Give the same name and extension in the your project. It would work.
Upvotes: 0
Reputation: 2768
Set a breakPoint to check "imgPath" result. If is empty, maybe you should add @2x to name:
NSString *imgPath =[[NSBundle mainBundle] pathForResource:@"google@2x" ofType:@"png"];
Upvotes: 0