我想使用NSLocale显示基于国家名称或国家/地区代码的货币符号我有所有国家/地区名称列表.假设我选择了USA然后返回$Currency
代码:
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *country = [locale displayNameForKey: NSLocaleCurrencyCode value: countryCode];
您可以使用以下代码构建自己的国家/地区代码列表和该国家/地区的货币符号:
Objective-C的:
- (void)listCountriesAndCurrencies {
NSArray *localeIds = [NSLocale availableLocaleIdentifiers];
NSMutableDictionary *countryCurrency = [NSMutableDictionary dictionary];
for (NSString *localeId in localeIds) {
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:localeId];
NSString *country = [locale objectForKey: NSLocaleCountryCode];
if (country && country.length == 2) {
NSString *currency = [locale objectForKey: NSLocaleCurrencySymbol];
countryCurrency[country] = currency;
}
}
NSArray *sorted = [countryCurrency.allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *country in sorted) {
NSString *currency = countryCurrency[country];
NSLog(@"country: %@, currency: %@", country, currency);
}
}
此代码以所有区域设置ID的列表开头.从那里创建每个关联的NSLocale.对于每个区域设置,将提取国家/地区代码和货币符号.这些用于构建国家代码和货币符号的字典,然后打印出来.
这是转换为Swift 3的相同代码:
func listCountriesAndCurrencies() {
let localeIds = Locale.availableIdentifiers
var countryCurrency = [String: String]()
for localeId in localeIds {
let locale = Locale(identifier: localeId)
if let country = locale.regionCode, country.characters.count == 2 {
if let currency = locale.currencySymbol {
countryCurrency[country] = currency
}
}
}
let sorted = countryCurrency.keys.sorted()
for country in sorted {
let currency = countryCurr