gpt4 book ai didi

ios - Xcode, swift : how to add multi-language support in an iOS app and have strings with placeholders and plurals?

转载 作者:IT王子 更新时间:2023-10-29 05:41:45 26 4
gpt4 key购买 nike

我需要在使用 Swift 在 Xcode 中编写的 iOS 应用程序中添加多语言支持。我需要本地化

  1. 静态字符串
  2. 带占位符的字符串
  3. 复数(数量字符串)

例如在Android中我们在XML文件中添加命名字符串和复数:

<string name="static_string">Hello world!</string>
<string name="placeholder_string">You have %2$d new messages.</string>
<plurals name="plural_string">
<item quantity="one">You have a new message.</item>
<item quantity="other">You have %2$d new messages.</item>
</plurals>

并遵循 Java 以编程方式获取字符串:

res.getString(R.string.placeholder_string, mailCount)
res.getQuantityString(R.plurals.plural_string, mailCount, mailCount)

我在找Swift(iOS)对应的解决方案

最佳答案

安装项目Localizations ,如截图所示,该项目有英语和俄语两种语言。

enter image description here

1: 创建一个名为 Localizable.strings 的文件并添加以下行

static_string="Hello world!";
placeholder_string="You have %d new messages.";

2: 我们在单独的文件中定义复数,让我们创建一个名为 Localizable.stringsdict 的文件并粘贴以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">

<!-- FIRST PLURAL STRING -->
<dict>
<key>plural_string</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@value@</string>
<key>value</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>You have a new message.</string>
<key>other</key>
<string>You have %d new messages.</string>
</dict>
</dict>
</dict>

<!-- NEXT PLURAL STRING -->
</plist>

接下来,本地化 Localizable.stringsdict文件,见屏幕截图,该文件已本地化为英语和俄语:

enter image description here

用法:

NSLocalizedString("static_string", comment: "") // Hello world!

String(format: NSLocalizedString("placeholder_string", comment: ""), 5) // You have 5 new messages.

let plural = NSLocalizedString("plural_string", comment: "")
String(format: plural, 1) // You have a new message.
String(format: plural, 2) // You have 2 new messages.

复数规则:在 XML 代码中,注意 <key>one</key><key>other</key> , 在这里你可以使用 zero , one , two , few , many , other取决于语言和您的要求。

使用以下链接获取有关语言特定复数规则的更多信息:http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html

如果您不熟悉字符串格式,本文也会有所帮助 https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

关于ios - Xcode, swift : how to add multi-language support in an iOS app and have strings with placeholders and plurals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30207436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com