代码之家  ›  专栏  ›  技术社区  ›  Whirlwind

如何在字符串目录中为不显示数字的标签实现复数?

  •  1
  • Whirlwind  · 技术社区  · 1 年前

    我正在本地化我的应用程序,我需要处理显示复数名词而不显示特定数字的文本视图。如:

    VStack(alignment: .center, spacing: 0) {
          Text("\(stepperValue)")
          Text("\(item.actionCount, specifier: specifier) \(literal: actionNameVariable)")
     }
    

    我正在使用此SO的解决方案 post 用于将文字与格式化值组合以形成本地化密钥:

    我试图在翻译中直接去掉这个数字。然而,当我有两种语言,以英语为基础语言时,从英语翻译中删除计数会导致:

    string catalogue screenshot

    我想这是有道理的,因为iOS不知道如何在没有实际数字的情况下处理复数。

    如果我用英语留下一个数字,在所有其他语言中,我可以在翻译中删除这个数字。然而,这并不是一个完整的解决方案,因为基本语言仍然显示数字。

    如何正确处理此问题?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Sweeper    1 年前

    您可以使用“open as”将xcstrings文件打开为JSON->“源代码”。

    enter image description here

    JSON结构应该被编辑成这样:

    // I've put comments in this JSON to explain things, 
    // but you should remove them in your actual code or it will not compile
    {
      "sourceLanguage" : "en",
      "strings" : {
        // "%lld Foo" is the key, "Foo" is the thing you want to pluralise
        "%lld Foo" : {
          "extractionState" : "manual",
          "localizations" : {
            // insert other languages in this JSON object...
            "en" : {
              "stringUnit" : {
                "state" : "translated",
                "value" : "%#@arg1@"
              },
              "substitutions" : {
                "arg1" : {
                  "argNum" : 1,
                  "formatSpecifier" : "lld", // repeat the format specifier in the key here
                  "variations" : {
                    "plural" : {
                      "one" : {
                        "stringUnit" : {
                          "state" : "translated",
                          "value" : "Foo" // singular form of the word
                        }
                      },
                      "other" : {
                        "stringUnit" : {
                          "state" : "translated",
                          "value" : "Foos" // plural form of the word
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "version" : "1.0"
    }
    

    (请注意此结构与中的结构之间的相似之处 this question 关于用字符串做同样的事情)

    然后 Text("\(1) Foo") 将输出“Foo”和 Text("\(2) Foo") 将输出“Foos”。


    也可以这样做 几乎 完全在字符串目录编辑器中。

    首先,添加一个使用 格式说明符,例如 %lld %lld Foo ,其中“Foo”是你想要多元化的东西。

    enter image description here

    接下来,使用“按复数变化”选项。这使您可以选择要更改的格式说明符。选择第一个。

    enter image description here

    现在看起来是这样的:

    enter image description here

    第二行的紫色“@arg1”就是我们一开始插入两个格式说明符的原因。出于某种原因,我找不到让Xcode以任何其他方式做到这一点的方法。

    现在我们可以删除其他我们不需要的绒毛。我们不在翻译中包括“%arg”(表示数字),而是只写单词的单数和复数形式。最终结果如下所示:

    enter image description here

    请注意,我已将第二个“%lld”从 %lld%lld Foo 。通过Xcode这样做实际上会导致Xcode崩溃(至少在15.3版本上),因此您必须直接编辑xcstrings文件中的JSON。但在那之后,Xcode应该可以正常工作。