关于国际化语言的信息获取
2018-07-20 本文已影响0人
微凉初夏
class MTLocation {
//获取对应国家名称的对应翻译
class func getLanguageName(with code: String) -> String {
//返回字符串
var string = ""
//当前语言与区域
let locale : NSLocale = NSLocale(localeIdentifier: code)
//获取国家数组
let languageArray = NSLocale.isoLanguageCodes
print("languageCode: = ", code)
// print("languageArray: == ", languageArray)
for languageCode in languageArray {
if code == languageCode {
if let displayName = locale.displayName(forKey: NSLocale.Key.languageCode, value: languageCode) {
string = displayName
print("name: === ", displayName)
}else{
string = ""
}
}
}
print("country name: ", string)
return string
}
//获取对应国家名称的翻译
class func getCountryCodeName(code: String, orgStr: String) -> String {
//返回字符串
var string = ""
//当前语言与区域
let locale : NSLocale = NSLocale.current as NSLocale
//获取国家数组
let countryArray = NSLocale.isoCountryCodes
for countryCode in countryArray {
if code == countryCode {
if let displayName = locale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode) {
string = displayName
}else{
string = orgStr
}
}
}
if string == "" {
string = orgStr
}
return string
}
//获取对应国家简码
class func getCountryCode(_ name: String) -> String? {
//返回字符串
var string: String?
//当前语言与区域
let locale : NSLocale = NSLocale.current as NSLocale
//获取国家数组
let countryArray = NSLocale.isoCountryCodes
for countryCode in countryArray {
if let displayName = locale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode) {
if name == displayName {
string = countryCode
}
}
}
return string
}
//换行处理
class func wrap(string: String) -> String {
print(string)
var str = ""
let array = string.components(separatedBy: " ")
var haveN = false
guard array.count > 1 else {
str = string
return str
}
str = array[0]
for i in 1..<array.count {
if array[i].contains("(") && !haveN {
str += "\n" + array[i]
haveN = true
}else {
if str.count > 10 {
if !haveN {
str += "\n" + array[i]
haveN = true
}
}else {
str += " " + array[i]
}
}
}
return str
}
//获取国家首字母
class func getInitials(org: String) -> String {
var string = org
string = String(org.prefix(upTo: org.index(org.startIndex, offsetBy: 1)))
let country = NSLocale.current.identifier
if country.contains("zh") {
let str = MTLocation.HanziToPinyin(org: string)
if let _first = str.first {
string = "\(_first)"
}
}
return string.uppercased()
}
//汉字转拼音
class func HanziToPinyin(org: String) -> String {
var string = ""
let str = NSMutableString(string: org) as CFMutableString
if CFStringTransform(str, nil, kCFStringTransformToLatin, false) == true {
if CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false) == true {
string = str as String
}
}else{
string = org
}
return string.capitalized
}
}