自最近的 swift 版本以来,可以使用多行字符串文字,可以轻松格式化多行字符串的外观。
不过,我正在寻找一种方法来本地化这样的字符串。
以下是用户可以发送的预配置邮件的文本示例:
mailComposerVC.setMessageBody("""
Hi,
I would like to share the following feedback:
""",
isHTML: false)
似乎没有办法将其正确转换为可本地化的 .strings 文件。
作为解决方法,我想出了单独本地化消息的每个部分并使用插值的解决方案:
let localisedGreeting = NSLocalizedString("Hi", comment: "")
let localisedMessage = NSLocalizedString("I would like to share the following feedback: ", comment: "")
mailComposerVC.setMessageBody("""
\(localisedGreeting),
\(localisedMessage)
""",
isHTML: false)
.strings 文件如下所示:
"Hi" = "Hallo";
"I would like to share the following feedback: " = "ich möchte folgendes Feedback geben: ";
有更好/更简洁的方法来做到这一点吗?
Localizable.strings
文件中的键和值都可以是多行。
与
“嗨, 我想分享以下反馈: ”=“你好, ich möchte folgendes 反馈意见: ”;
来电
let localizedMessage = NSLocalizedString("""
Hi,
I would like to share the following feedback:
""", comment: "")
按预期扩展。
但这可能不适用于本地化工具,而且也不适用 在 Localized.strings 中以正确的语法颜色显示,其中 可能会令人困惑。
我会使用短(单行)键,并将其本地化为所有 语言(包括默认语言英语)。
对我来说,这种文本和引号的布局有效(Swift 5.3,Xcode 12)
可本地化的字符串
"First Line
Second Line" = "Erste Linie
Zweite Linie";
实施
let lines = NSLocalizedString("""
First Line
Second Line
""", comment: "")
您还可以使用
" "
和这些运算符直接在单行中创建多行字符串:
\n
打破线条。\n\n
断行并创建空行swift 文件中的字符串:
let longString: LocalizedStringKey = "This is the first line. \n\n This is the second line after the blank line."
然后上面创建的字符串可以在
Localizable.strings
中使用,如下所示:
"This is the first line. \n\n This is the second line." = "This is the first line. \n\n This is the second line after the blank line.";
在 Xcode 15、Swift 5、iOS 17 上的 SwiftUI 上进行测试