2011-05-08 24 views
1

在代碼中更改UIImageView上的圖像時,圖像消失。這隻發生在iPod Touch設備上,而不發生在iPhone模擬器上。更改圖像時,UIImageView的圖像消失

在我的包我有一個名爲SomeImage.PNG

NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeImage" ofType:@"png"]; 
[self.background setImage:[[UIImage alloc] initWithContentsOfFile:path]]; 

我必須重申的圖像,能正常工作在iPhone模擬器,但不是iPod Touch的設備上。

請注意,圖像文件有一個大寫的文件擴展名,但在我的代碼中它是用小寫聲明。這就是問題。因此,要解決這個問題,將代碼改成這樣:

NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeImage" ofType:@"PNG"]; 
[self.background setImage:[[UIImage alloc] initWithContentsOfFile:path]]; 

我問,如果有一個「好」的方式做我在做什麼,所以我不碰到這樣的問題在未來到來。

回答

1

不是。不幸的是,iOS文件系統區分大小寫。

這樣的事情.....?

NSString *filename = @"SomeImage"; 
NSString *extension = @"png"; 
UIImage *img = nil; 
NSString *path = nil; 

path = [[NSBundle mainBundle] pathForResource:filename ofType:[extension lowercaseString]]; 
img = [[UIImage alloc] initWithContentsOfFile:path]; 

if (img == nil) { 
    path = [[NSBundle mainBundle] pathForResource:filename ofType:[extension uppercaseString]]; 
    img = [[UIImage alloc] initWithContentsOfFile:path]; 
} 
+0

謝謝,一個很好的答案,但從長遠來看可能是不必要的代碼量。我已經吸取了教訓! – Rots 2011-05-14 06:53:06