如何使用格式本地化 NSString

Kar*_*ren 2 objective-c string-formatting nsstring nslocalizedstring

如何使用格式本地化 NSString。

int value = 20;

NSString *str = @"hello";   

textLabel.text = [NSString stringWithFormat:@"%d %@", value, str];
Run Code Online (Sandbox Code Playgroud)

我试过

textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%d %@", @"%d %@"), value, str];
Run Code Online (Sandbox Code Playgroud)

但没有用。任何帮助表示赞赏。

Mec*_*cki 5

您的本地化字符串本身必须是格式模式:

"ValueAndStringFMT" = "Value %1$d and string %2$@";
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

textLabel.text = [NSString 
    stringWithFormat:NSLocalizedString(@"ValueAndStringFMT"),
    value, str
];
Run Code Online (Sandbox Code Playgroud)

为什么%1$d而不只是%d?所以你可以改变顺序。例如,在某些语言中,您可能希望交换顺序:

"ValueAndStringFMT" = "Cadena %2$@ y valor %1$d";
Run Code Online (Sandbox Code Playgroud)

当然,这有些危险,因为如果有人使用的占位符多于您的字符串调用提供的占位符或使用错误的类型,您的应用程序可能会崩溃。如果你想安全一点,你可以搜索并替换:

"ValueAndStringFMT" = "Value [[VALUE]] and string [[STRING]]";
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

NSString * string = NSLocalizedString(@"ValueAndStringFMT");
string = [string stringByReplacingOccurrencesOfString:@"[[VALUE]]" 
    withString:@(value).stringValue
];
string = [string stringByReplacingOccurrencesOfString:@"[[STRING]]" 
    withString:str
];
textLabel.text = string;
Run Code Online (Sandbox Code Playgroud)

这样,最坏的情况是占位符未展开,这意味着占位符明显打印在屏幕上,但至少您的应用程序不会因为有人搞乱了本地化字符串文件而崩溃。

如果您需要本地化其中一个格式变量,那么您需要首先在自己的步骤中执行此操作:

NSString * str = NSLocalizedString(@"hello");
Run Code Online (Sandbox Code Playgroud)