1. 程式人生 > >用Swift來獲取專案中的.bundle資原始檔

用Swift來獲取專案中的.bundle資原始檔

這是專案中的資原始檔XXX.bundle。
這裡寫圖片描述

首先,新建一個Bundle的擴充套件類:Bundle+XXX.swift

import UIKit

extension Bundle {

    // 定義一個靜態變數xxxBundle,用於獲取專案本地的Bundle檔案:XXX.bundle。
    static var xxxBundle: Bundle{
        return Bundle.init(path:Bundle.init(for: xxxComponent.self).path(forResource: "XXX", ofType: "bundle")!)!
    }

    // 定義一個靜態變數arrowImage,用於獲取圖片檔案:“arrow.png”。
static var arrowImage: UIImage{ return (UIImage.init(contentsOfFile: self.xxxBundle.path(forResource: "[email protected]", ofType: "png")!)?.withRenderingMode(UIImageRenderingMode.alwaysTemplate))! } // 類方法 class func localizedString(forKey key: String) -> String { return
self.localizedString(forKey: key, value: nil) } // 引數value為可選值,可以傳值為nil。 class func localizedString(forKey key: String, value: String?) -> String { var language = Locale.preferredLanguages.first! // (iOS獲取的語言字串比較不穩定)目前框架只處理en、zh-Hans、zh-Hant三種情況,其他按照系統預設處理 if language.
hasPrefix("en") { language = "en" } else if language.hasPrefix("zh") { language = "zh-Hans" } else { language = "en" } let bundle = Bundle.init(path: self.xxxBundle.path(forResource: language, ofType: "lproj")!) let v = bundle?.localizedString(forKey: key, value: value, table: nil) return Bundle.main.localizedString(forKey: key, value: v, table: nil) } }