gpt4 book ai didi

objective-c - 如何使用格式本地化 NSString

转载 作者:行者123 更新时间:2023-12-02 03:42:13 25 4
gpt4 key购买 nike

如何使用格式本地化 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");

关于objective-c - 如何使用格式本地化 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48192839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com