目标是能够在不必重新启动iOS Swift应用程序的情况下即时更改语言。
我正在使用类似下面的方法来实现它。
method_exchangeImplementations(
class_getInstanceMethod(Bundle.self, #selector(Bundle.localizedString(forKey:value:table:)))!,
class_getInstanceMethod(Bundle.self, #selector(Bundle.kd_localizedString(key:value:table:)))!
)
这适用于NSLocalized Strings,例如下面的
pickOneLabel.text = NSLocalizedString("Please choose one to continue..", comment: "")
因为语言更改后正在处理它。
但是对于全球声明,例如下面的例子。它不起作用
let requestStatuses = [
"open" : NSLocalizedString("Open Request", comment: ""),
"accepted" : NSLocalizedString("Booking - Confirmed", comment: ""),
"rejected" : NSLocalizedString("Booking - Rejected", comment: ""),
"expired" : NSLocalizedString("Request - Expired", comment: ""),
"cancelled" : NSLocalizedString("Booking - Cancelled", comment: ""),
"completed" : NSLocalizedString("Request - Completed", comment: "")
]
因为已经声明了上面的字典,所以在更改labgauge之前它会将原始语言字符串存储在其中。我真的不想重新声明它,因为它是多余的并且容易出错。有更好的解决方案吗?
答案 0 :(得分:0)
Haven未经过测试,但如何使用struct?
struct RequestStatus {
let open = NSLocalizedString("Open Request", comment: "")
// ...
}
let localizedTextOpen = RequestStatus().open // localized string on the fly?