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()
学swift语言能干什么}
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)
return LocalizationTool.shared.valueWithKey(key: self) }
}
再APPDelegate种调⽤,获取系统语⾔LocalizationTool.shared.checkLanguage()
字符串多语⾔赋值:
let cancel = "Cancel".localized
let ok = "OK".localized
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论