Swift多语言

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25639809/article/details/84985358

选择工程,添加一个语言
在这里插入图片描述

创建名为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

猜你喜欢

转载自blog.csdn.net/qq_25639809/article/details/84985358

相关文章