2013-02-20 45 views
30

NSLocalizedString我將如何使用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)]; 
+0

熱舔有正確的答案,但我也建議閱讀http://nshipster.com/nslocalizedstring/ – 2013-02-20 16:16:04

+0

我想我的答案不能處理嵌入的引號,但它們在原文中被打破。 – 2013-02-20 17:28:47

+0

本地化字符串的iOS實現的一個顯而易見的缺點是該註釋不包含在關鍵字的一部分中。出於這個原因,你可以有兩個不同的消息,使用相同的英文措辭,但不同的評論,操作系統不會(顯然)能夠消除歧義他們。 – 2013-02-20 17:32:28

回答

64
[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]; 
+0

啊,所以NSLocalizedString能識別'%@'? – 2013-02-20 21:56:21

+8

不,但stringWithFormat確實。 – 2013-02-20 23:13:57

+0

如果你在Swift上,你可以使用'String(格式:NSLocalizedString(「foo%@ baz」),「bar」)''。 – 2017-10-16 09:27:28

24

由於句子可用可變部分以不同的順序在某些語言中構建,那麼我認爲你應該使用位置參數[NSString stringWithFormat:]

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

這將加載英語以下字符串:

@"Is \"%[email protected]\" still correct for \"%[email protected]\" tap \"OK\" otherwise tap \"Change\" to choose new contact details" 

也許別的東西法語(我不知道法國人,所以我不會嘗試翻譯,但它很可能有以不同的順序,第一和第二個參數):

"French \"%[email protected]\" french \"%[email protected]\" french" 

您可以放心地格式化字符串作爲正常:

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

您不需要在英文版本中使用位置指定令牌(如果訂單不符合)。如果需要,他們仍然可以用在法語(或其他)中。 – 2013-02-20 17:34:00

+1

@HotLicks我認爲在任何地方使用它們都是有意義的。 – trojanfoe 2013-02-20 17:37:16

+1

在大多數情況下,錯誤又是另一回事。 – 2013-02-20 17:41:33

11

我只想添加一個非常有用的定義,我在很多項目中都使用它。

我已經添加了這個功能,我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); 
+0

工程就像一個魅力,非常優雅。 – agarcian 2014-10-13 20:16:50

+3

請注意,這會殺死'genstrings'工具,該工具只搜索對NSLocalizedStrings的直接引用。它不處理宏。 – AHM 2014-12-09 14:59:08