如何使用格式本地化 NSString
How to Localize NSString with format
如何使用格式本地化 NSString。
int value = 20;
NSString *str = @"hello";
textLabel.text = [NSString stringWithFormat:@"%d %@", value, str];
我试过了
textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%d %@", @"%d %@"), value, str];
但没用。感谢任何帮助。
您的本地化字符串本身必须是格式模式:
"ValueAndStringFMT" = "Value %1$d and string %2$@";
在您的代码中:
textLabel.text = [NSString
stringWithFormat:NSLocalizedString(@"ValueAndStringFMT"),
value, str
];
为什么 %1$d
而不仅仅是 %d
?所以你可以改变顺序。例如。在某些语言中,您可能希望调换顺序:
"ValueAndStringFMT" = "Cadena %2$@ y valor %1$d";
当然,这有点危险,因为如果有人使用比您的字符串调用提供的更多的占位符或使用错误的类型,您的应用程序可能会崩溃。如果你想安全起见,你可以搜索替换:
"ValueAndStringFMT" = "Value [[VALUE]] and string [[STRING]]";
在您的代码中:
NSString * string = NSLocalizedString(@"ValueAndStringFMT");
string = [string stringByReplacingOccurrencesOfString:@"[[VALUE]]"
withString:@(value).stringValue
];
string = [string stringByReplacingOccurrencesOfString:@"[[STRING]]"
withString:str
];
textLabel.text = string;
这样最坏的情况是占位符未展开,这意味着占位符明显打印在屏幕上,但至少您的应用不会因为有人弄乱了本地化字符串文件而崩溃。
如果您需要本地化其中一个格式变量,则需要先在自己的步骤中执行此操作:
NSString * str = NSLocalizedString(@"hello");
如何使用格式本地化 NSString。
int value = 20;
NSString *str = @"hello";
textLabel.text = [NSString stringWithFormat:@"%d %@", value, str];
我试过了
textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%d %@", @"%d %@"), value, str];
但没用。感谢任何帮助。
您的本地化字符串本身必须是格式模式:
"ValueAndStringFMT" = "Value %1$d and string %2$@";
在您的代码中:
textLabel.text = [NSString
stringWithFormat:NSLocalizedString(@"ValueAndStringFMT"),
value, str
];
为什么 %1$d
而不仅仅是 %d
?所以你可以改变顺序。例如。在某些语言中,您可能希望调换顺序:
"ValueAndStringFMT" = "Cadena %2$@ y valor %1$d";
当然,这有点危险,因为如果有人使用比您的字符串调用提供的更多的占位符或使用错误的类型,您的应用程序可能会崩溃。如果你想安全起见,你可以搜索替换:
"ValueAndStringFMT" = "Value [[VALUE]] and string [[STRING]]";
在您的代码中:
NSString * string = NSLocalizedString(@"ValueAndStringFMT");
string = [string stringByReplacingOccurrencesOfString:@"[[VALUE]]"
withString:@(value).stringValue
];
string = [string stringByReplacingOccurrencesOfString:@"[[STRING]]"
withString:str
];
textLabel.text = string;
这样最坏的情况是占位符未展开,这意味着占位符明显打印在屏幕上,但至少您的应用不会因为有人弄乱了本地化字符串文件而崩溃。
如果您需要本地化其中一个格式变量,则需要先在自己的步骤中执行此操作:
NSString * str = NSLocalizedString(@"hello");