You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import Foundation
import SwiftUI
import Combine
//
enum Language: String, CaseIterable {
case english = "en"
case chinese = "zh-Hans"
var displayName: String {
switch self {
case .english:
return "English"
case .chinese:
return "中文"
}
}
var flag: String {
switch self {
case .english:
return "🇺🇸"
case .chinese:
return "🇨🇳"
}
}
}
//
class LanguageManager: ObservableObject {
static let shared = LanguageManager()
@Published var currentLanguage: Language = .english
private let languageKey = "selected_language"
private init() {
loadLanguage()
}
//
private func loadLanguage() {
if let savedLanguage = UserDefaults.standard.string(forKey: languageKey),
let language = Language(rawValue: savedLanguage) {
currentLanguage = language
} else {
// 使
currentLanguage = .english
}
}
//
func switchLanguage(to language: Language) {
currentLanguage = language
UserDefaults.standard.set(language.rawValue, forKey: languageKey)
//
NotificationCenter.default.post(name: .languageChanged, object: language)
}
//
func localizedString(for key: String) -> String {
let bundle = Bundle.main
let language = currentLanguage.rawValue
if let path = bundle.path(forResource: language, ofType: "lproj"),
let languageBundle = Bundle(path: path) {
return languageBundle.localizedString(forKey: key, value: key, table: nil)
}
//
if let path = bundle.path(forResource: "en", ofType: "lproj"),
let languageBundle = Bundle(path: path) {
return languageBundle.localizedString(forKey: key, value: key, table: nil)
}
return key
}
}
//
extension String {
var localized: String {
return LanguageManager.shared.localizedString(for: self)
}
}
//
extension Notification.Name {
static let languageChanged = Notification.Name("languageChanged")
}