工具類:
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. 首先需要實(shí)例化工具類里的bundle,使用initUserLanguage方法键闺,可以把該方法寫在AppDelegate中热幔。
2. 其次寫一個(gè)擴(kuò)展或者類方法玄帕,調(diào)用getString方法國(guó)際化字符串(即:使用該方法代替原有的國(guó)際化方法)晨缴,當(dāng)然也可以每次直接使用getString方法,例如:
class func string(_ key: String) -> String {
return LanguageHelper.getString(key)
}
3. 接下來(lái)就是最重要的部分远搪,做一個(gè)語(yǔ)言選擇的界面或控件劣纲,利用工具類的方法實(shí)現(xiàn)這個(gè)類的功能,并通過監(jiān)聽實(shí)現(xiàn)以創(chuàng)建的視圖的語(yǔ)言國(guó)際化谁鳍,沒有創(chuàng)建的視圖在創(chuàng)建的時(shí)候會(huì)通過第2步的方法實(shí)現(xiàn)語(yǔ)言國(guó)際化癞季。代碼如下:(以界面為例,這是用故事版創(chuàng)建的一個(gè)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()
//當(dāng)前語(yǔ)言獲取
self.currentLang = UserDefaults.standard.value(forKey: UserLanguage) as? String
if Utils.isEmpty(currentLang) {//最開始沒有設(shè)置過語(yǔ)言時(shí)倘潜,獲取系統(tǒng)語(yǔ)言
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顯示數(shù)據(jù)
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轉(zhuǎn)換為當(dāng)前語(yǔ)言所對(duì)應(yīng)的字符串id
// let langStr = LanguageModel.getCurrentLangString(self.selectLang)
//設(shè)置語(yǔ)言
LanguageHelper.share.setLanguage(code)
//把selectLang轉(zhuǎn)換為當(dāng)前語(yǔ)言所對(duì)應(yīng)的字符串,賦值給currentLang
self.currentLang = self.selectLang
//國(guó)際化selectLang
// self.selectLang = langStr
//重新走一遍I18N方法
self.initLocalizableString()
self.tableView.reloadData()
//發(fā)出語(yǔ)言監(jiān)聽
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
}
}
}
這個(gè)工具對(duì)于不同的app需要作一些改變余佛,請(qǐng)自行斟酌!