Localizable.strings 键值对

Localizable.strings key-value pair

我想本地化“1 of 9”,1和9是int参数,我的代码如下

context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d", 
          "This text will be used to show page number on the screen"), 
          currentPageIndex + 1, pageCount];

生成的 Localizable.strings 就是这样显示的

/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";

我认为“=”左边的东西是键,“=”右边的东西是值,但我希望键看起来像"show_page_number"不包括格式“%” d",我该怎么办?我尝试用 "show_page_number" 替换“%d of %d”,但它不起作用。有什么建议吗?

如果您想完全控制密钥及其初始值,您需要使用 NSLocalizedStringWithDefaultValue 而不是 NSLocalizedString(使用密钥作为初始值)。

将您的代码更改为:

NSString *format = NSLocalizedStringWithDefaultValue(@"show_page_number", @"Localizable", NSBundle.mainBundle, @"%1$d of %2$d", @"This text will be used to show page number on the screen")
context = [NSString stringWithFormat:format, currentPageIndex + 1, pageCount];

当你运行genstrings时,你将获得:

/* This text will be used to show page number on the screen */
"show_page_number" = "%1$d of %2$d";

NSLocalizedString() 在运行时用值替换键。因此您可以使用任何字符串作为键,它会在运行时被替换为“%1$d of %2$d”。 在 Localizable 文件中添加字符串:

"show_page_number" = "%1$d of %2$d";

& 在代码中使用该键

context = [NSString stringWithFormat:NSLocalizedString(@"show_page_number", "This text will be used to show page number on the screen"), currentPageIndex + 1, pageCount];

在xcode项目中添加localizable.string文件。