【问题标题】:What is the 'correct' way localize programmatically created strings in Swift/Xcode?在 Swift/Xcode 中本地化以编程方式创建的字符串的“正确”方式是什么?
【发布时间】:2015-09-24 08:33:22
【问题描述】:

据我了解,本地化 Storyboard 对象相当简单:您有一个看起来像这样的文件:

/* Class = "NSMenuItem"; title = "Superscript"; ObjectID = "Rqc-34-cIF"; */
"Rqc-34-cIF.title" = "Superscript";

/* Class = "NSMenuItem"; title = "Select All"; ObjectID = "Ruw-6m-B2m"; */
"Ruw-6m-B2m.title" = "Select All";

/* Class = "NSTextFieldCell"; placeholderString = "0"; ObjectID = "RxW-oS-gX3"; */
"RxW-oS-gX3.placeholderString" = "0";

/* Class = "NSTextFieldCell"; title = "0"; ObjectID = "RxW-oS-gX3"; */
"RxW-oS-gX3.title" = "0";

/* Class = "NSMenuItem"; title = "Jump to Selection"; ObjectID = "S0p-oC-mLd"; */
"S0p-oC-mLd.title" = "Jump to Selection";

/* Class = "NSButtonCell"; title = "Play"; ObjectID = "qjC-b0-dMe"; */
"qjC-b0-dMe.title" = "Play";

并且要本地化每个字符串,只需将右侧的文本替换为其本地化的等效文本。很容易。

但是,如果代码显示的是标签或对话框,而字符串是在代码中定义的呢?例如:

if (dialogOKCancel("Invalid Path", text: "The file/path you selected does not exist, is not a valid sound file, or cannot be accessed by the program.")) {
    self.dismissController(self)
}

let result = dialogOKCancel("Discard Changes?", text: "Press Cancel to close this window and save your changes to \(filename), or OK to create a new file.")

我知道有许多不同的方法可以做到这一点(根据应用程序检测到的本地化设置在启动时定义字符串是我想到的一件事),但我想知道是否有“正确”/官方做我想要完成的事情的方法,或者如果没有,最好/最有效的方法是什么。

【问题讨论】:

标签: swift localization


【解决方案1】:

旧的 Objective C 访问方式是:

NSString *name = "Craig";
NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"Hello %@", nil),name];

Swift 版本如下:

let name = "Craig"
let msg = String(format: NSLocalizedString("Hello %@", comment: ""), name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多