2014-10-02 56 views
9

我需要將圖像包含在靜態庫中。 我創建了一個包並插入到我的圖像中,問題在於,如果將圖像直接包含在包中,似乎可以正常工作,但如果放入xcassets文件就會停止工作。無法在軟件包中的xcassets中加載圖像

我遵循了許多指南並在本網站上搜索解決方案。 最流行的解決方案是插入這行代碼:

[UIImage imageNamed:@"MyBundle.bundle/imageName"] 

但似乎不適合我

任何工作思路?

+0

面臨同樣的問題,你能解決這個問題嗎? – BaSha 2015-02-26 07:07:47

+0

@BaSha有可能使用IOS 8用這種方法: +(的UIImage *)imageNamed:(的NSString *)名稱inBundle:(一個NSBundle *)束compatibleWithTraitCollection:(UITraitCollection *)traitCollection; 與iOS 7的最佳解決方案是從xcassets刪除圖像文件 – Serluca 2015-02-26 09:38:22

+0

感謝,但我不得不在捆綁單獨添加圖像作爲iOS的7支持是必需的 – BaSha 2015-02-26 09:44:58

回答

9

有兩種方法來解決這個問題,

如果您的應用仍然支持IOS 7,你可以使用這個類別: https://gist.github.com/serluca/e4f6a47ffbc19fccc63e

否則,IOS 8日起蘋果增加了一個辦法做到這一點使用: + imageNamed:inBundle:compatibleWithTraitCollection:定義here

+0

知道有什麼辦法可以參考這裏面的Interface Builder? – jowie 2015-12-03 11:09:53

+1

@jowie您是否嘗試過這個http://stackoverflow.com/a/7733614/1728552 – Serluca 2015-12-03 12:38:51

+0

我做過但是指的是png,而不是.xcassets標識符。話雖如此,我沒有意識到,但我的問題進一步深入,因爲它不是從我的定製框架導入資產。 (希望)我會在我的另一個問題出來後再試一次。謝謝! – jowie 2015-12-03 15:05:25

7

運行相同的問題。看起來像1參數imageNamed方法中的XCAssets的內聯束支持已被破壞。雖然使用imageNamed有一個解決方法:inBundle:compatibleWithTraitCollection:小心,這只是iOS8!

NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"static_lib_bundle_name" ofType:@"bundle"]]; 
UIImage *image = [UIImage imageNamed:@"image_in_the_xcassets_you_want" inBundle:bundle compatibleWithTraitCollection:nil]; 

注:traitCollection設爲零通過主屏幕特性爲每apple docs(我不太得到什麼意思不過,如果有誰知道請發表評論!)。

+0

任何好辦法在iOS7中做到這一點? – user1010819 2014-12-20 12:56:53

+3

所以我一直有同樣的問題,看起來像是xcode直接將xcassets編譯爲二進制文件(.car)並複製到主包中,這意味着xcassets不能包含在捆綁資源中。 https://devforums.apple.com/message/968859#968859 – 2015-02-06 11:49:39

2

我們的圖片放置在Images.xcassets,我們曾與在IBDesignable加載圖像的問題。下面的代碼確實在界面生成的預覽和應用工作,以及:

NSBundle* bundle = [NSBundle bundleForClass:[self class]]; 
UIImage* image = [UIImage imageNamed:@"image.jpg" inBundle:bundle compatibleWithTraitCollection:nil]; 
+0

正如我說如果你使用的iOS 7,你可以使用我的類別這種方法可從IOS 8開始,而不是以https://gist.github。 com/serluca/e4f6a47ffbc19fccc63e – Serluca 2015-05-01 13:09:07

2

對於斯威夫特2。 1:

let bundle = pathToBundle // define for your app or framework 
if let image = UIImage(named: "drop_arrow", inBundle: bundle, compatibleWithTraitCollection: nil) { 
    // process image 
}