组件代码的上传:上传组件至CocoaPods
在组件工程的.podspec配置中说到,本地资源加载的配置方式有两种:
# 方式一:会自动创建一个.bundle包,将资源放到.bundle下
# bundle名称可以自定义,在下面配置
s.resource_bundles = {
'TRectDetector' => ['TRectDetector/Assets/resource/*.png']
}
# 方式二:资源直接放到目录下
s.resources = ['TRectDetector/Assets/resource/*.png']
因为在OC中Podfile一般不使用use_frameworks!,所以我们不使用use_frameworks!,分别用两种方式加载资源,使用Example项目pod install进行测试:
方式一:自动生成bundle
//使用此方式加载图片 必须是全名例如: test@2x.png
- (NSString *)bundleForImage:(NSString *)name {
NSString *path = [[NSBundle mainBundle] pathForResource:@"TRectDetector" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:path];
if (!bundle) {
return @"";
}
NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
return [bundle pathForResource:imgName ofType:nil];
}
//使用
self.gridImageView.image = [UIImage imageWithContentsOfFile:[self bundleForImage:@"camera_grid"]];
方式二:直接置于目录下
//直接用imageNamed加载,不用全名
self.gridImageView.image = [UIImage imageNamed:@"camera_grid"];
我们也可以手动把资源放进TRectDetector.bundle里面:在Assets目录下创建一个TRectDetector.bundle,把资源放进bundle里面,修改.podspec文件
s.resources = ['TRectDetector/Assets/resource/*.bundle']
重新执行pod install,然后可以发现与方式就是一样的。这个时候使用方式一的加载方式也能正常显示。
===================== 分割线 ================
前面说到,Podfile文件中,如果不使用swift或者dynamic frameworks,一般不使用use_frameworks!,那么用和不用有什么区别嘞,下面就说说这个:
1、不使用use_frameworks!时,pod导入进来的三方库一般编译成static Library(.a),解压后是一堆可执行二进制文件(.o),如果和项目中的类名相同会冲突;因只包含二进制文件,体积较小,资源文件需另外提供。
2、那么使用use_frameworks!时,三方库最终编译成framework(static || dynamic),包含代码签名、头文件、二进制执行文件和静态资源。所有的.framework会存放在mainbundle下的Frameworks目录下。也就是说使用s.resources加载资源的方式,这个时候用imageNamed并不能加载图片,因为资源并不在mainbundle下。
下面是使用use_frameworks!,方式一和方式二的加载情况:
方式一:自动生成bundle (use_frameworks!)
- (NSString *)bundleForImage:(NSString *)name {
NSString *path = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"TRectDetector.framework/TRectDetector.bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:path];
NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
return [bundle pathForResource:imgName ofType:nil];
}
方式二:直接置于目录下(use_frameworks!)
- (NSString *)bundleForImage:(NSString *)name {
// 没有自动创建bundle TRectDetector.bundle
NSString *path = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"TRectDetector.framework"];
NSBundle *bundle = [NSBundle bundleWithPath:path];
NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
return [bundle pathForResource:imgName ofType:nil];
}
最后附上TRectDetector链接地址: