May Phyu
May Phyu

Reputation: 905

How to localize alert message box in Swift

My alert box message code is

let alertController = UIAlertController(title: "Hello!", message:
                            "Good Morning Everyone!", preferredStyle: UIAlertControllerStyle.Alert)
                        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))

I want to translate the text
Hello and Good Morning Everyone!.
How to implement this in swift?

Upvotes: 0

Views: 2739

Answers (2)

May Phyu
May Phyu

Reputation: 905

Now, I got the solution!

 let alertController = UIAlertController(title: "Hello!", message:
                            "Good Morning Everyone!", preferredStyle: UIAlertControllerStyle.Alert)
                        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))


                        alertController.title = NSLocalizedString("Hello!", comment: "")
                        alertController.message = NSLocalizedString("Good Morning Everyone!", comment: "")

Upvotes: 0

Viktor Simkó
Viktor Simkó

Reputation: 2637

You can use NSLocalizedString for this.

let title = NSLocalizedString("Hello!", comment: "alertController title")
let message = NSLocalizedString("Good Morning Everyone!", comment: "alertController message")

let alertController = UIAlertController(
  title: title, 
  message: message, 
  preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))

Then cd into the project directory and use genstrings utility to generate the Localizable.strings file. Then add it to the project, and select it.
In the File Inspector click on Localize..., then select the languages you want to use.
This will create the Localizable.strings files for the specific languages.

Or you can select your project then go to Editor->Export For Localization...
This will create an XLIFF file, in which you can do the translation,
then import it back using Editor->Import Localizations...

Upvotes: 2

Related Questions