類庫就是一個二進制代碼的集合,類庫中使用自定義的類和資源時,需要手動導入 build phase-copy files中添加
如果是添加了自定義類,選擇對應的.h文件導入
Library_1.png
如果需要添加資源,比如圖片,由于Xcode默認在編譯時會把所有的素材文件導入到mainBundle中蘑辑,為了避免與使用靜態(tài)庫的程序沖突
在靜態(tài)庫中如果要使用圖片素材墅茉,會利用bundle的手段
(比如類庫中的一張圖片名稱是123,自己項目中也有一張圖片123,項目設置資源圖片時就會沖突)
為了演示,在類庫中添加一個返回圖片的方法
.h聲明:
@interface JSLibrary : NSObject
+ (UIImage *)creatImage;
@end
.m文件實現(xiàn):
@implementation JSLibrary
+ (UIImage *)creatImage{
return [UIImage imageNamed:@"imageSources.bundle/mao"];
}
@end
如果類庫中直接拖拽資源圖片,項目中存在和類庫同名的資源圖片,那么就會出現(xiàn)資源沖突的問題,只需要將存放資源包的文件夾添加.bundle后綴,那么bundle文件就搞定了:
Library_2.png
接下來拖到類庫中:
Library_3.png
這樣還沒完,還需要手動導入資源文件
(類庫中使用自定義的類和資源時,需要手動導入 build phase-copy files中添加)
Library_4.png
這樣Command + B生成的.a文件就可以使用了
導入項目:
Library_5.png
#import "ViewController.h"
#import "JSLibrary.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc]initWithImage:[JSLibrary creatImage]];
[self.view addSubview:imageView];
imageView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
[self.view addConstraint:centerX];
NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
[self.view addConstraint:centerY];
}
@end
這樣就可以顯示bundle路徑下的資源圖片了:
Library_6.png