7

我正在尝试这个:

NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];

它创建 NSLocale 对象,但不包含任何区域信息。例如,

[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];

返回零;

知道如何从货币代码中获取 NSLocale 吗?

4

4 回答 4

8

正如一些访客在 pastebin 中发布的那样:

NSDictionary *components = [NSDictionary dictionaryWithObject:@"USD" forKey:NSLocaleCurrencyCode];
NSString *localeIdentifier = [NSLocale localeIdentifierFromComponents:components];
NSLocale *localeForDefaultCurrency = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];

[localeForDefaultCurrency objectForKey:NSLocaleCountryCode];
于 2013-06-09T00:31:23.387 回答
6
    NSDictionary *localeInfo = @{NSLocaleCurrencyCode: currencyCode, NSLocaleLanguageCode: [[NSLocale preferredLanguages] objectAtIndex:0]};

    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:
                        [NSLocale localeIdentifierFromComponents:localeInfo]];
于 2013-12-23T18:34:02.400 回答
5

有一些技巧,比如使用 id 创建语言环境,但不是像“en_US”这样的普通语言环境 id,而是传递货币代码“USD”、“EUR”等,它似乎对 eur 和 usd 有效,但我可以检查它但是这个恕我直言,这是错误的方式。

我知道的唯一正确方法是获取所有语言环境,然后循环检查它们的货币代码以与您拥有的货币代码进行比较。这样,当您找到代码时,您将停止循环。

- (NSLocale *) findLocaleByCurrencyCode:(NSString *)_currencyCode
{
        NSArray *locales = [NSLocale availableLocaleIdentifiers];
        NSLocale *locale = nil;
        NSString *localeId;

        for (localeId in locales) {
                locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeId] autorelease];
                NSString *code = [locale objectForKey:NSLocaleCurrencyCode];
                if ([code isEqualToString:_currencyCode])
                        break;
                else
                        locale = nil;
        }

        /* For some codes that locale cannot be found, init it different way. */
        if (locale == nil) {
                NSDictionary *components = [NSDictionary dictionaryWithObject:_currencyCode
                                                                       forKey:NSLocaleCurrencyCode];

                localeId = [NSLocale localeIdentifierFromComponents:components];
                locale = [[NSLocale alloc] initWithLocaleIdentifier:localeId];
        }
        return locale;
}
于 2012-07-20T08:31:33.357 回答
1

您可以在Swift中使用扩展的强大功能:

extension NSLocale {

    static func currencySymbolFromCode(code: String) -> String? {
       let localeIdentifier = NSLocale.localeIdentifierFromComponents([NSLocaleCurrencyCode : code])
       let locale = NSLocale(localeIdentifier: localeIdentifier)
       return locale.objectForKey(NSLocaleCurrencySymbol) as? String
    }

}

这样,在您的代码中的任何地方:

let code = "EUR"
let price = 10
if let currencySymbol = NSLocale.currencySymbolFromCode(code) as? String {
    print("You have to pay \(price)\(currencySymbol)")
}
于 2016-03-11T16:57:41.117 回答