2012-02-02 25 views
2

我想本地化我的遊戲。我的一些標籤就像[@「分數:%i」,分數],分數可以是任意數字。所以我仍然可以使用字符串文件本地化? 這就是我目前做的,但很多工作iOS本地化,帶數字和單詞的標籤

CCLabelTTF* bestLabelWord = [Helper createLocalizedLabelWithStringUpperCase:@"BEST" color:ccBLACK]; 
    CCLabelTTF* bestLabelNumber = [Helper createUnlocalizedLabelWithString:[NSString stringWithFormat:@"%i", bestScore] color: ccBLACK]; 
    bestLabelWord.anchorPoint = ccp(0, 0.5f); 
    bestLabelNumber.anchorPoint = ccp(0, 0.5f); 
    bestLabelWord.position = ccp(menuPosX, menuPosY2); 
    bestLabelNumber.position = ccp(menuPosX + bestLabelWord.contentSize.width + 5, menuPosY2); 
    [self addChild:bestLabelWord z:kZLabel]; 
    [self addChild:bestLabelNumber z:kZLabel]; 

這裏我分開@「得分」,@「%i」的,將比分追成2個標籤(字和數字),並分開放置。 那麼我怎麼能把它們放到一個標籤?我可以把「NSString stringWithFormat」放在localization.strings文件中嗎?

回答

2

是的,你可以這樣做。它看起來像這樣(未編譯;希望沒有錯字):

NSString *scoreFormat = NSLocalizedString(@"Score: %d", @"Score format"); 
NSString *scoreString = [NSString stringWithFormat:scoreFormat, bestScore]; 

您的字符串文件對於這個用英語將是:

/* Score format */ 
"Score: %d" = "Score: %d"; 

%d沒有區別和%i。它們都是由標準規定的。我個人更喜歡錶示它是「十進制」(與十六進制的%x相比),而不是它是「整數」(與浮點數%f相比)。但是這沒關係。

您應該將整個格式語句包含在字符串文件中。您正在本地化整個格式聲明Score: %d。這樣做的基本原理是允許訂單可能不同的語言。例如,如果有一種語言的正確譯文是"%d score"或語言有意義,那麼您將不得不說相當於Score: %d pointsScore: %d number

如果您不想要這種類型的本地化,並且您將始終在後面的標籤和數字之後放一個冒號,無論使用何種語言,那麼您都可以像原始代碼一樣將本地化標籤或者是這樣的:

NSString *localizedLabel = NSLocalizedString(@"Score", @"Score"); 
NSString *scoreString = [NSString stringWithFormat:@"%@: %d", localizedLabel, bestScore]; 

你應該避免調用NSLocalizedString具有可變參數作爲你所建議的。這是令人困惑的,並可能妨礙使用genstrings來創建您的字符串文件。這就是說,下面的代碼是沒有問題的:

NSString * const kScoreLabelKey = @"Score"; 
NSString * const kPriceLabelKey = @"Price"; 

NSString *GetLocalizedStringForKeyValue(NSString *key, NSInteger value) 
{ 
    NSString *label = [[NSBundle mainBundle] localizedStringForKey:key value:nil table:@"Labels"]; 
    NSString *valueLabel = [NSString stringWithFormat:@": %d", value]; 
    return [label stringByAppendingString:valueLabel]; 
} 

... 

NSString *label = GetLocalizedStringForKeyValue(kScoreLabelKey, bestScore); 

... 

(在Labels.strings):

"Score" = "Score"; 
"Price" = "Price"; 

注意事項:

  • 我創建了一個獨立的字符串文件此稱爲Labels.strings。這樣,它不會影響使用genstrings和主Localizeable.string.
  • 我用鍵的字符串常量。這將所有在一個地方使用的字符串放在文件的頂部,這樣可以很容易地對Labels.strings進行審覈。
+0

什麼是@「Score格式」? – OMGPOP 2012-02-02 02:35:11

+0

我應該把什麼字符串文件? – OMGPOP 2012-02-02 02:36:01

+0

http://stackoverflow.com/questions/1442822/what-is-second-param-of-nslocalizedstring – 2012-02-02 02:36:29