ios开发之使用bundle来管理资源文件
轉載自:http://blog.csdn.net/kylinbl/article/details/9047209
(chenyong 將資源文件夾弄成bundle格式的特簡單單,只需要把后綴名改成.bundle即可)?
在ios開發中為了方便管理資源文件,可以使用bundle的方式來進行管理,比如kkgridview里就是把所需的圖片文件全部放在一個bundle來管理的 .
切記目前iOS中只允許使用bundle管理資源文件和國際化信息,不支持代碼的打包。
在xcode中只能夠創建setting bundle,會默認創建一些配置文件,在xcode中無法直接刪除,這也許不是我們需要的。
那么如何使用最簡單的方法創建一個bundle呢?
1 創建一個文件夾
2 將該文件夾重命名為a.bundle
3 將a.bundle拖入到xcode中即可
當然這樣處理之后,取圖片之類的文件,使用的方法就不一樣了,以取iphone_52x52.png圖片為例:
? ? ? ??NSString?*bundlePath = [[NSBundle?mainBundle].resourcePath?stringByAppendingPathComponent:@"My.bundle"];
? ? ? ??NSBundle?*bundle = [NSBundle?bundleWithPath:bundlePath];
? ? ? ??UIImage?*(^getBundleImage)(NSString?*) = ^(NSString?*n) {
? ? ? ? ? ??return?[UIImage?imageWithContentsOfFile:[bundle?pathForResource:n?ofType:@"png"]];
? ? ? ? };
? ? ? ??UIImage?*myImg = getBundleImage(@"iphone_52x52");
?代碼是蠻長一塊,為了方便使用,我們可以寫一個UIImage的類別,在類別中加入此方法,這樣用起來就簡單多了:
(chenyong因為用了categary,所以在制作靜態庫時需要注意那個 _all_load什么的。。。見上篇文章)
- (UIImage?*)imagesNamedFromCustomBundle:(NSString?*)imgName
{
? ??NSString?*bundlePath = [[NSBundle?mainBundle].resourcePath?stringByAppendingPathComponent:@"My.bundle"];
? ??NSBundle?*bundle = [NSBundle?bundleWithPath:bundlePath];
? ??NSString?*img_path = [bundle?pathForResource:imgName?ofType:@"png"];
? ??return?[UIImage?imageWithContentsOfFile:img_path];
}
UIImage?* img? = [self?imagesNamedFromCustomBundle:@"iphone_52x52"];
測試了下,發現一點小問題,為了兼容retina屏,有iphone_52x52.png和iphone_52x52@2x.png,兩張圖片,
當我們用UIImage?* img = [UIImage imageNamed:@"iphone_52x52"];這種方式取圖片時,會根據你是不是retina屏
來返回不同的圖片,如果這兩張圖你只提供了一張,那么也可以正常運行,只是圖片會按比例進行拉伸。
在測試上面的imagesNamedFromCustomBundle方法時,提供兩張圖片和只提供iphone_52x52.png時,兩種屏下面都正常,但如果只提供了iphone_52x52@2x.png這張圖片,那么無論是普通屏還是retina屏,都會找不到圖片。
調試分析了下,是在[bundle?pathForResource:imgName?ofType:@"png"];這里出了問題,返回的path都是nil,把上面的方法改成下面這樣:
- (UIImage?*)imagesNamedFromCustomBundle:(NSString?*)imgName
{
? ??NSString?*bundlePath = [[NSBundle?mainBundle].resourcePath?stringByAppendingPathComponent:@"testLocalVirable.bundle"];
? ??NSString?*img_path = [bundlePath?stringByAppendingPathComponent:imgName];
? ??return?[UIImage?imageWithContentsOfFile:img_path];
}
這樣在來測試,retina屏正常了,普通屏還是找不到圖片。
分析了半天也沒找到解決方法,知識還是有限啊,看來要去請教下大牛才行了;
現階段的處理方法就是別偷懶,提供完整的兩張圖片就ok了。
這里有老外的一篇講Resource Bundles的文章:http://www.cocoanetics.com/2012/05/resource-bundles/
粗略過了一遍,有些地方也沒看懂,記下來,有空花時間好好看看。
bundle的本質就是一個文件夾。當然在iOS中還可以干很多事情,詳細資料請參考:
https://developer.apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html#//apple_ref/doc/uid/10000123i-CH100-SW7
總結
以上是生活随笔為你收集整理的ios开发之使用bundle来管理资源文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 集团类企业信息化原则与思路
- 下一篇: 呼叫中心_VOIP技术介绍