版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1、第一步先cd进入要创建私有库的目录,然后输入如下命令创建私有库:
// ChatFramework是要创建的私有库的名字
pod lib create ChatFramework
- 1
- 2
然后按照提示回答几个问题即可:
2、命令执行完成后会自动创建并打开一个叫ChatFramework的工程,文件结构如下:
先简单介绍下:
ChatFramework.podspec:文件是私有库的配置文件
ChatFramework:该文件夹是存放私有库的类和资源的地方
Example:是根据上图提示,我们选择创建的demo工程,如果选择No,则不会生成此工程
3、现在该是写代码测试私有库的时候啦
3.1 调用私有库的代码
在私有库里创建一个Person类,增加一个sayHello方法,然后执行命令pod install重新安装一下私有库。
在Example工程里,先导入头文件,再创建一个Person类,可以看到控制台Hello, world!成功打印。
3.2 调用私有库的图片资源
在调用私有库的图片的时候如果使用[UIImage imageNamed:@”login_logo_image”];这种方式去获取图片是拿不到的。因为这种方式是从mainBundle里面找,然鹅,私有库的图片并没有被拷贝到mainBundle里。
加载图片的正确姿势如下:
1.先把图片等资源打包成bundle
2.写一个分类,用来加载自己的bundle
#import "NSBundle+Library.h"
#import "CustomView.h"
@implementation NSBundle (Library)
+ (NSBundle *)myLibraryBundle {
return [self bundleWithURL:[self myLibraryBundleURL]];
}
+ (NSURL *)myLibraryBundleURL {
NSBundle *bundle = [NSBundle bundleForClass:[CustomView class]];
return [bundle URLForResource:@"ChatFramework" withExtension:@"bundle"];
}
@end
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
再写一个分类,用来加载bundle里面的图片
#import "UIImage+Library.h"
#import "NSBundle+Library.h"
@implementation UIImage (Library)
+ (UIImage *)bundleImageNamed:(NSString *)name {
return [self imageNamed:name inBundle:[NSBundle myLibraryBundle]];
}
+ (UIImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0
return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
#elif __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
return [UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:nil]];
#else
if ([UIImage respondsToSelector:@selector(imageNamed:inBundle:compatibleWithTraitCollection:)]) {
return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
} else {
return [UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:nil]];
}
#endif
}
@end
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
最后在测试类里面写一个暴露图片的方法,供外界调用
#import "CustomView.h"
#import "UIImage+Library.h"
@implementation CustomView
+ (UIImage *)logoImage
{
return [UIImage bundleImageNamed:@"login_logo_image"];
}
@end
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
准备工作做好后,还有一个最重要的步骤:修改podspec配置文件
以上步骤完成后,在Example中调用一下:
#import "JYViewController.h"
#import <ChatFramework/CustomView.h>
@interface JYViewController ()
@end
@implementation JYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Person *p = [[Person alloc] init];
// [p sayHello];
// 加载图片
UIImageView *imageView = [[UIImageView alloc] initWithImage:[CustomView logoImage]];
imageView.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:imageView];
}
@end
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Ok,到此结束!