How to get current language code with Swift?

前端 未结 13 2079
难免孤独
难免孤独 2020-12-07 11:06

I want get the language code of the device (en, es...) in my app written with Swift. How can get this?

I\'m trying this:

var preferredLanguages : NSL         


        
13条回答
  •  孤城傲影
    2020-12-07 11:30

    This is what I use in Swift 5 Xcode 11:

    Inside the class variables:

    let languagePrefix = Bundle.main.preferredLocalizations.first?.prefix(2)
    

    This comes as a string. It returns 2 characters, i.e. "en", "es", "de"...

    From this I can easily determine what language to display:

     if languagePrefix == "es" { self.flipCard.setTitle("última carta", for: .normal) }
     if languagePrefix == "en" { self.flipCard.setTitle("Last Card", for: .normal) }
    

    If you want the full information of the language, then remove ?.prefex(2)

提交回复
热议问题