Xcode 10中的本地化

时间:2019-02-05 22:32:46

标签: ios xcode localization nslocalizedstring

我有一个应用程序,其中所有面向用户的字符串都使用NSLocalizableString()。我从未对应用程序进行过本地化,因此我观看了WWDC 2018视频New Localization Workflows in Xcode 10。从那里我创建了一个新项目,一个Single View App。默认情况下,基本本地化处于启用状态。在故事板上,我添加了一个UILabel并将其约束在视图的中心。我在视图控制器中为其添加了插座:

@IBOutlet weak var label: UILabel!

然后在viewDidLoad中设置其文本:

label.text = NSLocalizedString("Hello World", comment: "")

构建并运行,可以正常运行。

现在我添加一个本地化。我选择项目并添加西班牙语。

enter image description here

然后在编辑器菜单上导出本地化...。我通过以下路径打开文件:

es.xcloc -> LocalizedContents -> es.xliff

在其中找到“ Hello World”键,并将其值更改为“ Hola Mundo”并保存文件。

...
<file original="MyProject/en.lproj/Localizable.strings" datatype="plaintext" source-language="en" target-language="es">
    <header>
      <tool tool-id="com.apple.dt.xcode" tool-name="Xcode" tool-version="10.1" build-num="10B61"/>
    </header>
    <body>
      <trans-unit id="Hello World">
        <source>Hola Mundo</source>
        <note>No comment provided by engineer.</note>
      </trans-unit>
    </body>
  </file>
...

然后返回Xcode并导入本地化。这是第一个问题:

enter image description here

为什么这是不匹配的翻译?

我继续进口。我按如下方式编辑方案:

enter image description here

我跑步时得到“ HELLO WORLD”。它是大写的,因为这是本地化调试,指示没有翻译。

我想念什么?

1 个答案:

答案 0 :(得分:1)

我们这里有一些问题。首先,当您执行NSLocalizedString("Hello World", comment: "")时,实际上是在尝试使用键Hello World来获取本地化的字符串,并且由于Xcode找不到该键,因此它会返回您自己设置的键标签。因此,为获得最佳实践,请考虑使用不包含空格的键。也许像hello-world-label。然后,将是:

NSLocalizedString("hello-world-label", comment: "")

导出本地化后,将生成以下内容:

<trans-unit id="hello-world-label">
    <source>hello-world-label</source>
    <note>No comment provided by engineer.</note>
</trans-unit>

现在您必须添加<target>标记以指定实际的翻译。因此:

<trans-unit id="hello-world-label">
    <source>hello-world-label</source>
    <target>Hola Mundo</target>
    <note>No comment provided by engineer.</note>
</trans-unit>

然后只需导入本地化,就可以了。

编辑

这样做之后,应该已经生成一个Localizable.strings文件。单击它,然后在Xcode右侧File Inspector下的Localization中进行查看。您会认为该文件仅针对Spanish进行了本地化。因此,继续并选择English复选框。然后,您的Localizable.strings将可以同时使用英语和西班牙语进行编辑,如下图所示:

enter image description here

现在,您可以编辑该文件的英文版,以在应用程序中同时使用两种语言。