一、新建Bundle
示例是在主工程SwiftTest的子工程Home里進行。
因為iOS框架中沒有Bundle,所以要在macOS中創(chuàng)建Bundle。

新建Bundle.png
二、往Bundle中添加資源
將資源文件(如圖片、xib文件)拖入剛創(chuàng)建的Bundle文件夾下。新創(chuàng)建xib時可以直接創(chuàng)建到Bundle文件夾目錄下。

給Bundle添加資源.png

添加完資源示例.png
三、配置Bundle
1.修改Base SDK為iOS

修改Base SDK.png
2.iOS Deployment Target改為需要支持的最低版本

修改Deployment版本.png
注意:
可以不用修改Deployment版本,但是不修改的話,后續(xù)如果使用手動編譯、且在真機上進行編譯,則可能會報Deployment Target不匹配的錯。

真機編譯Bundle時Deployment Target不匹配報錯.png
3.Enable Bitcode設(shè)置為No,其中只放資源文件,否則編譯會報錯

設(shè)置Enable Bitcode.png

Enable Bitcode未設(shè)置為No報錯.png
- COMBINE_HIDPI_IMAGES設(shè)置為NO
iOS 創(chuàng)建Bundle時放入的圖片資源(.png)在默認配置下會被轉(zhuǎn)為.tiff格式,使用的時候找不到。因為在iOS中創(chuàng)建bundle時會用一個“hack”,為了使所有的運行需要更改一個配置。找到bundle的工程,Buld Settings > COMBINE_HIDPI_IMAGES設(shè)置為NO

修改COMBINE_HIDPI_IMAGES.png

COMBINE_HIDPI_IMAGES為YES時打包后成果.png

COMBINE_HIDPI_IMAGES為NO時打包后成果.png
四、編譯Bundle
在Scheme中選擇Bundle作為target、設(shè)備選Any iOS Device或者具體真機進行編譯,不先編譯的話,使用的時候會報錯。

編譯Bundle.png

未編譯就使用報錯.png
注意:
- 如果動態(tài)庫Target的Dependencies中設(shè)置了Bundle依賴,則可不手動提前編譯Bundle。
五、使用Bundle里的資源文件
1.在動態(tài)庫Target的Copy Bundle Resources、Dependencies中添加Bundle。

引用Bundle.png
注意:
- 必須在Dependencies (圖中3.1)中也添加一下Bundle依賴,否則會出現(xiàn)
編譯運行不報錯,打包報錯的問題。

未設(shè)置Dependencies依賴打包報錯.png
2.使用xib
let bundle = Bundle(for: HomeViewController.self)
// 加載方式1:如果未在Copy Bundle Resources中引用Bundle時會出現(xiàn)crash現(xiàn)象
let nibs1 = bundle.loadNibNamed("HomeResource.bundle/ToolBar", owner: nil, options: nil)
// 加載方式2:推薦使用
guard let resourceURL = bundle.url(forResource: "HomeResource", withExtension: "bundle") else { return }
let nibs2 = Bundle(url: resourceURL)?.loadNibNamed("ToolBar", owner: nil, options: nil)
// 讀取xib中視圖并展示
if let xibView = nibs?.first as? UIView {
xibView.frame = CGRect(x: 20, y: 180, width: 250, height: 44)
view.addSubview(xibView)
}
3.使用圖片
let imageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 80, height: 80))
let bundle = Bundle(for: HomeViewController.self)
// 加載方式1
imageView.image = UIImage(named: "HomeResource.bundle/load_failure", in: bundle, compatibleWith: nil)
// 加載方式2
guard let resourceURL = bundle.url(forResource: "HomeResource", withExtension: "bundle") else { return }
imageView.image = UIImage(named: "load_failure", in: Bundle(url: resourceURL), compatibleWith: nil)
六、修改資源文件后的處理
- 通常情況下(動態(tài)庫Target未在Dependencies中設(shè)置Bundle依賴試),Bundle中資源文件有修改時,需重新編譯Bundle,其使用方(動態(tài)庫)才能讀取修改后的資源。
- 在動態(tài)庫Target的Dependencies中添加對Bundle的依賴,則每次編譯動態(tài)庫時也會自動編譯Bundle,從而能隨時讀取Bundle中資源的更新。

Dependencies中設(shè)置Bundle依賴.png