1. 程式人生 > >Swift多語言

Swift多語言

選擇工程,新增一個語言
在這裡插入圖片描述

建立名為Localization的strings檔案,並在右側勾選語言
在這裡插入圖片描述
在strings檔案裡分別定義字串的值
在這裡插入圖片描述

"Cancel" = "Cancel";
"OK" = "OK";
"Cancel" = "取消";
"OK" = "確定";

新建檔案,處理語言的獲取和儲存修改

import Foundation

enum Language {
    case english
    case chinese
}

class LocalizationTool {
    
    static let shared = LocalizationTool()
    
    let defaults = UserDefaults.standard
    var bundle: Bundle?
    var currentLanguage: Language = .english
    
    func valueWithKey(key: String) -> String {
        let bundle = LocalizationTool.shared.bundle
        if let bundle = bundle {
            return NSLocalizedString(key, tableName: "Localization", bundle: bundle, value: "", comment: "")
        } else {
            return NSLocalizedString(key, comment: "")
        }
    }
    
    func setLanguage(language: Language) {
        if currentLanguage == language {
            return
        }
        switch language {
        case .english:
            defaults.set("en", forKey: Keys.language)
            break
        case .chinese:
            defaults.set("cn", forKey: Keys.language)
            break
        }
        currentLanguage = getLanguage()
    }
    
    func checkLanguage() {
        currentLanguage = getLanguage()
    }
    
    private func getLanguage() -> Language {
        var str = ""
        if let language = defaults.value(forKey: Dex4DKeys.language) as? String {
            str = language == "cn" ? "zh-Hans" : "en"
        } else {
            str = getSystemLanguage()
        }
        if let path = Bundle.main.path(forResource:str , ofType: "lproj") {
            bundle = Bundle(path: path)
        }
        return str == "en" ? .english : .chinese
    }
    
    private func getSystemLanguage() -> String {
        let preferredLang = Bundle.main.preferredLocalizations.first! as NSString
        switch String(describing: preferredLang) {
        case "en-US", "en-CN":
            return "en"
        case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
            return "zh-Hans"
        default:
            return "en"
        }
    }
}

extension String {
    var localized: String {
        return LocalizationTool.shared.valueWithKey(key: self)
    }
}

再APPDelegate種呼叫,獲取系統語言

LocalizationTool.shared.checkLanguage()

字串多語言賦值:

let cancel = "Cancel".localized
let ok = "OK".localized