我应该如何使用多个参数进行本地化?

时间:2016-08-10 06:48:36

标签: ios objective-c cocoa-touch localization

我们说我有以下字符串:

[NSString stringWithFormat:@"Booked for %@ at %@", colleagueName, time];

我意识到我已经忘记了将字符串本地化,所以我将其替换掉:

[NSString stringWithFormat:NSLocalizedString(@"bookings.bookedFor", "Booked for user at time"), colleagueName, time];

现在进行翻译时,我发现语言X需要反过来的参数;更贴近的事情:

<time> for booking of <colleague> is done.

现在我需要将格式化字符串的第二个参数设为time,将第三个参数设为colleagueName,这是解决这个问题的最佳方法吗?

2 个答案:

答案 0 :(得分:1)

通常情况下,我的同事几乎在我问到这个问题时就找到了解决方案!显然,Objective-C有位置参数

这些位置是1索引的,因此%1$@指的是第一个参数。

NSString *firstParam = @"1st";
NSString *secondParam = @"2nd";
NSLog(@"First %1$@ Second: %2$@", firstParam, secondParam);
NSLog(@"Second %2$@ First: %1$@", firstParam, secondParam);

打印:

First 1st Second: 2nd   
Second 2nd First: 1st

答案 1 :(得分:-1)

您可以尝试这样:

    NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([language isEqualToString:@"X"]) {//X is language code like "fr","de"
      [NSString stringWithFormat:NSLocalizedString(@"bookings.bookedFor", "Booked for user at time"), time, colleagueName];
    } else {
      [NSString stringWithFormat:NSLocalizedString(@"bookings.bookedFor", "Booked for user at time"), colleagueName,time];
    }