美文网首页Swift工作笔记
swift 获取当前系统语言

swift 获取当前系统语言

作者: 晓蜻蜓 | 来源:发表于2016-08-20 18:24 被阅读2021次

    OC语言:

    + (NSString*)getPreferredLanguage{
    
            NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    
            NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    
            NSString* preferredLang = [languages objectAtIndex:0];
    
            return preferredLang;
    
    }
    

    swift 语言:

    func getCurrentLanguage() -> String{
    
           let defs = NSserDefaults.standardUserDefaults()
    
           let languages = defs.objectForKey("AppleLanguages")//获取系统支持的所有语言集合
    
           let preferredLanguage = languages!.objectAtIndex(0)//集合第一个元素为当前语言
    
           return String(prefrredLanguage)//若当前系统为英文,则返回en_US
    
    }
    

    swift升级版:

       static func getCurrentLanguage() -> String {
    //        let defs = UserDefaults.standard
    //        let languages = defs.object(forKey: "AppleLanguages")
    //        let preferredLang = (languages! as AnyObject).object(0)
            let preferredLang = Bundle.main.preferredLocalizations.first! as NSString
    //        let preferredLang = (languages! as AnyObject).object(0)
            Log.debug("当前系统语言:\(preferredLang)")
            
            switch String(describing: preferredLang) {
            case "en-US", "en-CN":
                return "en"//英文
            case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
                return "cn"//中文
            default:
                return "en"
            }
        }
    
    

    相关文章

      网友评论

      本文标题:swift 获取当前系统语言

      本文链接:https://www.haomeiwen.com/subject/jbyisttx.html