swift - 在 Swift/Xcode 中本地化以编程方式创建的字符串的 'correct' 方式是什么?

标签 swift localization

据我了解,本地化 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.")

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

最佳答案

旧的 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)

关于swift - 在 Swift/Xcode 中本地化以编程方式创建的字符串的 'correct' 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729590/

相关文章:

swift - 在 Swift 5 中从 AWS S3 下载文本文件

android - 在云上的iOS和Android之间共享本地化

ios - 有没有办法让 GPS 给出的位置更准确?

javascript - Dojo 本地化 - 当本地化字符串包含单引号时,data-dojo-props 失败

ios - 为什么我的 UIVisualEffectView 显示在 View 层次结构中,但不在我的设备中?

ios - 容器 View 中的 UIPageViewController

ios - 使用 dataTaskWithRequest 填充 uitableview

swift - 如何使 NSWindow 从按钮操作中出现 (Swift 3) (Mac OSX)

c# - 将 Docker 上 ASP.NET Core 2.2 中的默认时区更改为 24 小时时间格式

javascript - 使用 Knockoutjs 动态调整页面内容以适应用户选择的语言?