將資源文件打成bundle

封裝SDK等組件時(shí),為了不在宿主項(xiàng)目中額外配置資源文件,通常將SDK所用資源文件打成.bundle文件。

創(chuàng)建Bundle

1.選中工程目錄。點(diǎn)擊添加Target
  1. 選擇macOS,搜索bundle,選擇Bundle,下一步。
  2. 設(shè)置bundle名字
  3. 選中bundle的Target,在Build settings 下搜索 combine, 將COMBINE_HIDPI_IMAGES值改為No。(不然打包成bundle中的圖片會(huì)編程.tiff格式)
  4. 新建一個(gè)分組,用來裝需要打包的資源文件

將資源文件放入Bundle

  1. 將外部的資源文件拖入文件夾內(nèi),并選擇Target為創(chuàng)建的Bundle
  2. 將資源文件導(dǎo)入后的結(jié)構(gòu)

生成.bundle文件

  1. 選中Bundel工程,編譯。
  2. 點(diǎn)擊Product中Show Build Folder in Finder
  3. 在Debug內(nèi)有生成的.bundle文件
  4. 顯示包內(nèi)容,可以檢查一下生成的bundle文件中是否包含所需資源文件

使用.bundle

  1. 沒問題了就可以將.bundle文件拖入項(xiàng)目中。這次用的Target是宿主,所以選擇宿主Target。
  2. 使用
    2.1 OC
@interface UIImage (BundleImage)
+ (UIImage *)loadBundleImage:(NSString *)imageName;
@end

@implementation UIImage (BundleImage)

+ (UIImage *)loadBundleImage:(NSString *)imageName {
    
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"TestAppBundle" ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    return [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];
    
}

@end

調(diào)用:

UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 18, 18)];
img.image = [UIImage loadBundleImage:@"arrowLeft"];
[self.view addSubview:img];

2.2 Swift

class ChatbotBundle {
    static func getZKSmartBundle() -> Bundle {
        if let bundleURL = Bundle.main.url(forResource: "ChatbotBundle", withExtension: "bundle"),
           let bundle = Bundle(url: bundleURL) {
            return bundle
        } else {
            fatalError("ZKSmart.bundle not found.")
        }
    }
}

extension UIImage {
    static func loadBundleImage(_ name: String) -> UIImage {
        return UIImage(named: name, in: ChatbotBundle.getZKSmartBundle(), compatibleWith: nil)!
    }
}

調(diào)用:

lazy var backBtn: UIButton = {
  let button = UIButton(type: .custom)
  button.backgroundColor = .clear
  button.setImage(UIImage.loadBundleImage("arrowLeft"), for: .normal)
  return button
}()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容