iOS本地化:复数和NSNumberFormatter

问题描述 投票:5回答:2

是否可以将NSNumberFormatter用于NSNumber格式化以及stringdict中的复数规则?

我需要下一个带格式的数字(以千位分隔)。如果我使用NSNumberFormatter格式化数字-我收到了NSString,并且我不再使用复数规则,因为iOS无法从NSString中了解该短语是单数还是复数名词。

[1锻炼”单身

1,732,123锻炼”复数

NSNumberFormatter* numberFormatter = ...;
[NSString stringWithFormat:NSLocalizedString(@"%@ Workouts!", @"n Workout(s)"), [numberFormatter stringFromNumber:value]]
ios objective-c cocoa-touch
2个回答
10
投票

经过一些研究,我发现不用NSNumberFormatter就可以分隔成千上万个数字,只需使用localizedStringWithFormat。这也使我可以使用复数规则。

[NSString localizedStringWithFormat:NSLocalizedString(@"%@ Workouts!", @"n Workout(s)"), value]

Localizable.stringsdict

...
<key>%@ Workouts</key>
<dict>
    <key>NSStringLocalizedFormatKey</key>
    <string>%#@Workouts@</string>
    <key>Workouts</key>
    <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>NSStringFormatValueTypeKey</key>
        <string>@</string>
        <key>one</key>
        <string>%@ Workout!</string>
        <key>other</key>
        <string>%@ Workouts!</string>
    </dict>
</dict>
....

0
投票

您可以将数字和带格式的字符串(2个参数)传递到NSLocalizedString基本思想是使用数字控制复数规则,但使用格式化的字符串显示。

我以Swift中的Decimal为例:

let number: Decimal = 13456
let formatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.groupingSeparator = ","
    return formatter
}()

let formattedNumberString = formatter.string(from: number as NSDecimalNumber) ?? "-" // "13,456"

let format = NSLocalizedString(
    "workouts",
    comment: "arg1 is for number, arg2 is for formatted string"
)

let resultString = String.localizedStringWithFormat(
    format, 
    number as NSDecimalNumber, 
    formattedNumberString
)

Localizable.stringsdict中,您可以这样做:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>workouts</key>
    <dict>
      <key>NSStringLocalizedFormatKey</key>
      <string>%1$#@number@</string>
      <key>number</key>
      <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>NSStringFormatValueTypeKey</key>
        <string>@</string>
        <key>one</key>
        <string>%2$@ Workout!</string>
        <key>other</key>
        <string>%2$@ Workouts!</string>
      </dict>
    </dict>
  </dict>
</plist>

在此示例中,resultString13,456 Workouts!。如果更改number = 1,则resultString将为1 Workout!

© www.soinside.com 2019 - 2024. All rights reserved.