工具类:
let UserLanguage = "UserLanguage"
let AppleLanguages = "AppleLanguages"
class LanguageHelper: NSObject {
static let share = LanguageHelper()
let def = UserDefaults.standard
var bundle : Bundle?
class func getString(_ key:String) -> String{
let bundle = LanguageHelper.share.bundle
let str = bundle?.localizedString(forKey: key, value: nil, table: nil)
return str!
}
func initUserLanguage() {
var string: String = def.value(forKey: UserLanguage) as? String ?? ""
if string == "" {
if let languages = def.object(forKey: AppleLanguages) as? NSArray {
if languages.count > 0 {
if let current = languages.object(at: 0) as? String {
string = current
def.set(current.components(separatedBy: "-").first, forKey: UserLanguage)
def.synchronize()
}
}
}
}
switch string {
case LangKey.ES_latam:
break
default:
if let str = string.components(separatedBy: "-").first {
string = str
}
break
}
var path = Bundle.main.path(forResource:string , ofType: "lproj")
if path == nil {
path = Bundle.main.path(forResource:"en" , ofType: "lproj")
}
bundle = Bundle(path: path!)
}
func setLanguage(_ langeuage:String) {
let path = Bundle.main.path(forResource:langeuage , ofType: "lproj")
bundle = Bundle(path: path!)
def.set(langeuage, forKey: UserLanguage)
def.synchronize()
}
}
使用方法:
1. 首先需要实例化工具类里的bundle,使用initUserLanguage方法,可以把该方法写在AppDelegate中。
2. 其次写一个扩展或者类方法,调用getString方法国际化字符串(即:使用该方法代替原有的国际化方法),当然也可以每次直接使用getString方法,例如:
class func string(_ key: String) -> String {
return LanguageHelper.getString(key)
}
3. 接下来就是最重要的部分,做一个语言选择的界面或控件,利用工具类的方法实现这个类的功能,并通过监听实现以创建的视图的语言国际化,没有创建的视图在创建的时候会通过第2步的方法实现语言国际化。代码如下:(以界面为例,这是用故事版创建的一个tableview的界面)
class LanguageViewController: UITableViewController {
@IBOutlet var doneBtn: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
self.initUI()
self.initLocalizableString()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private var currentLang: String!
private var selectLang: String!
private var dataArray: Array<String> = Array()
private func initUI() {
//init
self.dataArray = LanguageModel.getLangArr()
//当前语言获取
self.currentLang = UserDefaults.standard.value(forKey: UserLanguage) as? String
if Utils.isEmpty(currentLang) {//最开始没有设置过语言时,获取系统语言
if let langs = UserDefaults.standard.object(forKey: AppleLanguages) as? Array<String> {
if langs.count > 0 {
self.currentLang = langs[0]
}
}
}
//特殊处理
switch self.currentLang {
case LangKey.ES_latam:
break
default:
self.currentLang = self.currentLang.components(separatedBy: "-").first
break
}
//UI显示数据
self.currentLang = LanguageModel.getCurrentLang(currentLang)
self.selectLang = self.currentLang
self.doneBtn.action = #selector(doneClick)
self.doneBtn.target = self
self.doneBtn.titleFont(UIFont.systemFont(ofSize: 13))
}
@objc func doneClick(_ button: UIBarButtonItem) {
self.setCurrLanguage()
}
private func initLocalizableString() {
self.navigationItem.title = i18n(I18N.Identifier(rawValue: "id_navigation_title_language")!)
self.doneBtn.title = i18n(I18N.Identifier(rawValue: "id_navigation_right_button_done")!)
}
private func setCurrLanguage() {
let code = LanguageModel.getCurrentLangCode(self.selectLang)
//把selectLang转换为当前语言所对应的字符串id
// let langStr = LanguageModel.getCurrentLangString(self.selectLang)
//设置语言
LanguageHelper.share.setLanguage(code)
//把selectLang转换为当前语言所对应的字符串,赋值给currentLang
self.currentLang = self.selectLang
//国际化selectLang
// self.selectLang = langStr
//重新走一遍I18N方法
self.initLocalizableString()
self.tableView.reloadData()
//发出语言监听
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ChangeLanguage), object: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id = "LanguageCell"
let cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath)
let str = dataArray[indexPath.row]
cell.textLabel?.text = str
if str == self.currentLang {
cell.accessoryType = .checkmark
}else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.setAllCell()
let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = .checkmark
self.selectLang = cell?.textLabel?.text
}
private func setAllCell() {
for i in 0..<langKey.count {
let cell = tableView.cellForRow(at: IndexPath(row: i, section: 0))
cell?.accessoryType = .none
}
}
}
这个工具对于不同的app需要作一些改变,请自行斟酌!