Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save phynet/af6a70aa3078648410af to your computer and use it in GitHub Desktop.
Save phynet/af6a70aa3078648410af to your computer and use it in GitHub Desktop.
Using UIAlertController with NSLocalizedString

##Using UIAlertController with NSLocalizedString Because I tend to localize everything in my apps, UIAlertController needed to be localized as well. So, I wrote a struct to simplify the way I use NSLocalizedWithString (which happens to be a long piece of code), and so I could use it in all my classes.

Use an extension (remember, an extension is like a category in Obj-c)

extension String {

   var localized: String {
      return String.localizedStringWithFormat(NSLocalizedString(self,comment: ""))
   }

   func localizedWithComment(comment:String) -> String {
      return String.localizedStringWithFormat(NSLocalizedString(self,comment: comment))
   }
}

Use Constants for better manipulation

let errortitle = "alertErrorTitle".localized
let errormessage = "alertErrorMessage".localized
let cancel = "cancelAlert".localized

And the AlertController piece of code:

func showAlertError(){

    var alertController = UIAlertController(title: errortitle,
                                        message: errormessage,
                                        preferredStyle: .Alert)

    let cancelAction = UIAlertAction(title: cancel, style: .Cancel) {
      (action) in
      //whatever action you want,  put it here
    }
    alertController.addAction(cancelAction)
    presentViewController(alertController, animated: true, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment