62 lines
1.9 KiB
Swift
62 lines
1.9 KiB
Swift
//
|
||
// SPLocalizedManager.swift
|
||
// ShortPlay
|
||
//
|
||
// Created by 曾觉新 on 2025/4/8.
|
||
//
|
||
|
||
import UIKit
|
||
|
||
class SPLocalizedManager: NSObject {
|
||
static let shared = SPLocalizedManager()
|
||
|
||
private let userDefaultsKey = "AppLocalized"
|
||
|
||
// 获取当前语言代码(如果用户未手动设置,则返回系统语言)
|
||
var currentLocalizedKey: String {
|
||
get {
|
||
// return UserDefaults.standard.string(forKey: userDefaultsKey) ?? Locale.preferredLanguages.first ?? "en"
|
||
return "en"
|
||
}
|
||
set {
|
||
UserDefaults.standard.set(newValue, forKey: userDefaultsKey)
|
||
UserDefaults.standard.synchronize()
|
||
NotificationCenter.default.post(name: SPLocalizedManager.localizedDidChange, object: nil)
|
||
}
|
||
}
|
||
|
||
// 判断是否跟随系统
|
||
var isFollowingSystem: Bool {
|
||
return UserDefaults.standard.string(forKey: userDefaultsKey) == nil
|
||
}
|
||
|
||
// 还原为系统默认语言
|
||
func resetToSystemLanguage() {
|
||
UserDefaults.standard.removeObject(forKey: userDefaultsKey)
|
||
UserDefaults.standard.synchronize()
|
||
}
|
||
|
||
// 获取本地化字符串
|
||
func localizedString(forKey key: String, tableName: String? = nil) -> String {
|
||
if let selectedLanguage = UserDefaults.standard.string(forKey: userDefaultsKey),
|
||
let bundlePath = Bundle.main.path(forResource: selectedLanguage, ofType: "lproj"),
|
||
let bundle = Bundle(path: bundlePath) {
|
||
return bundle.localizedString(forKey: key, value: nil, table: tableName)
|
||
} else {
|
||
return NSLocalizedString(key, tableName: tableName, bundle: .main, value: "", comment: "")
|
||
}
|
||
}
|
||
}
|
||
|
||
extension SPLocalizedManager {
|
||
|
||
static let localizedDidChange = Notification.Name(rawValue: "SPLocalizedManager.localizedDidChange")
|
||
|
||
}
|
||
|
||
extension String {
|
||
var localized: String {
|
||
return SPLocalizedManager.shared.localizedString(forKey: self)
|
||
}
|
||
}
|