在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].resourcePathstringByAppendingPathComponent:@"My.bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
UIImage *(^getBundleImage)(NSString *) = ^(NSString *n) {
return [UIImage imageWithContentsOfFile:[bundle pathForResource:nofType:@"png"]];
};
UIImage *myImg = getBundleImage(@"iphone_52x52");
代碼是蠻長一塊,為了方便使用,我們可以寫一個UIImage的類別,在類別中加入此方法,這樣用起來就簡單多了:
- (UIImage *)imagesNamedFromCustomBundle:(NSString *)imgName
{
NSString *bundlePath = [[NSBundle mainBundle].resourcePathstringByAppendingPathComponent:@"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].resourcePathstringByAppendingPathComponent:@"testLocalVirable.bundle"];
NSString *img_path = [bundlePath stringByAppendingPathComponent:imgName];
return [UIImage imageWithContentsOfFile:img_path];
}
調用方式改成:UIImage * img = [self imagesNamedFromCustomBundle:@"iphone_52x52.png"];//把擴展名加上了
這樣在來測試,retina屏正常了,普通屏還是找不到圖片。
分析了半天也沒找到解決方法,知識還是有限啊,看來要去請教下大牛才行了;
現階段的處理方法就是別偷懶,提供完整的兩張圖片就ok了。
這里有老外的一篇講Resource Bundles的文章:http://www.cocoanetics.com/2012/05/resource-bundles/
粗略過了一遍,有些地方也沒看懂,記下來,有空花時間好好看看。
bundle的本質就是一個文件夾。當然在iOS中還可以干很多事情,詳細資料請參考:
