格式化字符串的 NSLocalizedString

41

我该如何使用NSLocalizedString处理这个字符串:

[NSString stringWithFormat:@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", individual.contactInfo, individual.name];

在使用stringWithFormat之前,我以以下方式使用它:

[NSString stringWithFormat:@"%d %@", itemCount, NSLocalizedString(@"number of items", nil)];

Hot Licks 给出了正确的答案,但我也建议阅读 http://nshipster.com/nslocalizedstring/。 - Chris Wagner
我猜我的答案没有处理嵌入引号,但它们在原始文本中已经损坏了。 - Hot Licks
iOS本地化字符串的一个明显缺陷是,注释不作为键的一部分包含在内。因此,您可以拥有两个具有相同英文措辞但不同注释的不同消息,操作系统将无法(显然)消除歧义。 - Hot Licks
这是一篇关于Swift本地化的非常好的文章,适用于强大的架构。 - Mendy
4个回答

74
[NSString stringWithFormat:NSLocalizedString(@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", @"Query if parm 1 is still correct for parm 2"), individual.contactInfo, individual.name];

啊,所以NSLocalizedString可以识别%@ - Peter Warbo
9
不行,但是stringWithFormat可以。 - Hot Licks
5
如果你正在使用Swift,你可以使用String(format: NSLocalizedString("foo %@ baz"), "bar")。这将通过格式化本地化字符串,将"bar"插入到"foo %@ baz"的位置上。 - Henrik N

34

在一些语言中,给定的句子可以使用不同的顺序构建可变部分,因此我认为您应该使用带有[NSString stringWithFormat:]的位置参数:

给定句子中的可变部分在一些语言中可以以不同的顺序进行构建,因此我建议您使用带有[NSString stringWithFormat:]的位置参数。

NSString *format = NSLocalizedString(@"number_of_items", @"Number of items");

哪个会为英语加载以下字符串:

@"Is \"%1$@\" still correct for \"%2$@\" tap \"OK\" otherwise tap \"Change\" to choose new contact details"

而对于法语,也许还有其他的内容(我不懂法语,所以不会尝试翻译,但是第一个和第二个参数的顺序可能会不同):

"French \"%2$@\" french \"%1$@\" french"

你可以像平常一样安全地对字符串进行格式化:

NSString *translated = [NSString stringWithFormat:format individual.contactInfo, individual.name];

在英文版本中,如果顺序符合要求,则不需要使用位置指定标记。如果需要,仍然可以在法语(或其他语言)中使用它们。 - Hot Licks
2
@HotLicks 如果使用的话,我认为在任何地方都使用它们是有意义的。 - trojanfoe

13

我只想添加一个非常有用的定义,我在很多项目中都使用它。

我已经将这个函数添加到我的header prefix文件中:

#define NSLocalizedFormatString(fmt, ...) [NSString stringWithFormat:NSLocalizedString(fmt, nil), __VA_ARGS__]

这允许您定义一个本地化字符串,例如以下内容:

 "ExampleScreenAuthorizationDescriptionLbl"= "I authorize the payment of %@ to %@.";

并且它可以通过以下方式使用:

self.labelAuthorizationText.text = NSLocalizedFormatString(@"ExampleScreenAuthorizationDescriptionLbl", self.formattedAmount, self.companyQualifier);

运行起来非常好,而且非常优雅。 - agarcian
3
请注意,这将破坏 genstrings 工具的功能,该工具仅搜索对 NSLocalizedString 的直接引用,而不处理宏。 - AHM

3

Swift

//本地化字符串

"my-localized-string" = "foo %@ baz";

示例:

最初的回答:

这是一个关于本地化字符串的示例代码,其中使用了占位符“%@”来代表变量。在需要使用此本地化字符串的位置,可以通过替换占位符来动态地将变量插入到字符串中。

myLabel.text = String(format: NSLocalizedString("my-localized-string", 
                                       comment: "foo %@ baz"), "bar") //foo bar baz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接