打包.framework可以参考文章《将使用了CocoaPods的IOS项目打包为Framework+打包后的测试+PrefixHeader.pch使用》
打包.bundle可以参考文章《IOS项目打包bundle》
问题描述:
使用静态库项目已经将.framework、.bundle包打好,并且.framework中的代码使用了.bundle中的图片资源文件,.framework中对图片资源文件的加载是从原IOS项目中直接拷贝过来的。
现在要新建一个测试Demo,在测试Demo中添加.framework、.bundle,并在测试Demo中的ViewController.m中添加代码,推出.framework中的主操作界面。
因为静态库项目和测试demo中均存在ViewController.h、ViewController.m。因此,将测试Demo中的ViewController.h、ViewController.m重命名,如修改为ViewController1.h、ViewController1.m,并对应修改这两个文件内部代码中的ViewController为ViewController1。修改测试demo中Main.storyboard中关联的ViewController为ViewController1,如下图所示:
在ViewController.m中添加的推出.framework中主操作界面的代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
TabBarViewController *vc = [[TabBarViewController alloc]init];
((AppDelegate *)([UIApplication sharedApplication].delegate)).window.rootViewController = vc;
}
执行Command+B,编译成功build success。运行项目,在模拟器中可以推出.framework的主操作页面,但是页面中涉及到的所有图片都不显示。
解决方案:
.framework中涉及到的主页面中图片的加载方式需要进行修改,并且静态库项目中放置在Assets.xcassets中@2x,@3x的图片需要从Assets.xcassets中拷贝出来放置到静态库项目中,然后直接将这些图片添加到Bundle对应的Copy Bundle Resources中,重新打包.bundle
修改静态库项目中涉及到的上述所有图片加载方式的代码,可以使用全局搜索,如下图所示:
图片加载方式修改为如下:
NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath
stringByAppendingPathComponent:@"/MyBundle.bundle"];
NSBundle *resource_bundle = [NSBundle bundleWithPath:bundlePath];
UIImage *image = [UIImage imageNamed:@"banner"
inBundle:resource_bundle
compatibleWithTraitCollection:nil];
例子如下:
静态库项目中,搜索出来的其中一处涉及到touxiang.png图片的原代码如下:
-(UIImageView *)touxiangImage{
if (!_touxiangImage) {
_touxiangImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, 35, 50, 50)];
_touxiangImage.layer.masksToBounds = YES;
_touxiangImage.layer.cornerRadius = 23;
touxiangImage.image = [UIImage imageNamed:@"touxiang"];
[_touxiangImage.layer setBorderWidth:0.25];
[_touxiangImage.layer setMasksToBounds:YES];
}
return _touxiangImage;
}
修改后的代码如下:
-(UIImageView *)touxiangImage{
if (!_touxiangImage) {
_touxiangImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, 35, 50, 50)];
_touxiangImage.layer.masksToBounds = YES;
_touxiangImage.layer.cornerRadius = 23;
// _touxiangImage.image = [UIImage imageNamed:@"touxiang"];
NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath
stringByAppendingPathComponent:@"/MyBundle.bundle"];
NSBundle *resource_bundle = [NSBundle bundleWithPath:bundlePath];
_touxiangImage.image = [UIImage imageNamed:@"touxiang"
inBundle:resource_bundle
compatibleWithTraitCollection:nil];
[_touxiangImage.layer setBorderWidth:0.25];
[_touxiangImage.layer setMasksToBounds:YES];
}
return _touxiangImage;
}
同理,将bundle中所有图片在静态库项目中涉及的加载方式代码进行上述修改。然后,重新打包.framework、.bundle,导入到测试Demo中,再次尝试执行测试Demo,在测试Demo中推出的.framework的主操作页面中,图片显示正常。