func countryName(from countryCode: String) -> String {
if let name = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: countryCode) {
// Country name was found
return name
} else {
// Country name cannot be found
return countryCode
}
}
// get the localized country name (in my case, it's US English)
let englishLocale = Locale.init(identifier: "en_US")
// get the current locale
let currentLocale = Locale.current
var theEnglishName : String? = englishLocale.displayName(forKey: NSLocaleIdentifier, value: currentLocale.localeIdentifier)
if let theEnglishName = theEnglishName
{
let countryName = theEnglishName.sliceFrom("(", to: ")")
print("the localized country name is \(countryName)")
}
import Foundation
extension String {
func sliceFrom(start: String, to: String) -> String? {
return (range(of: start)?.upperBound).flatMap({ (sInd) -> String? in
(range(of: to, range: sInd..<endIndex)?.lowerBound).map { eInd in
substring(with: sInd..<eInd)
}
})
}
}
在应用程序委托中使用
let englishLocale : NSLocale = NSLocale.init(localeIdentifier : "en_US")
// get the current locale
let currentLocale = NSLocale.current
var theEnglishName : String? = englishLocale.displayName(forKey: NSLocale.Key.identifier, value: currentLocale.identifier)
if let theEnglishName = theEnglishName
{
countryName = theEnglishName.sliceFrom(start: "(", to: ")")
print("the localized country name is \(countryName)")
}
9条答案
按热度按时间bvjveswy1#
一个超级干净的Swift 3版本是:
如果您想本地化名称,可以将区域设置标识符更改为例如Locale.current.identifier。上面的示例仅适用于英语。
fzwojiic2#
雨燕3
cczfrluj3#
试着这样做:
使用此辅助函数that I found here:
我通过研究this related question发现了这一点。
pw136qt24#
下面是一个紧凑的swift 4版本,一直为我工作:
或者一个优雅的扩展名,如@Memon建议的:
wh6knrhe5#
如果你想打印国家名称和国旗这里是代码
如何使用
输出将为:
yb3bgrhw6#
试试这个
cygmwpex7#
使用Swift3
在应用程序委托中使用
3okqufwl8#
雨燕4
vtwuwzda9#
注:如果您手动输入
localIdentifier
,则表示iOS 8未列出所有国家/地区名称(例如:"en_美国")