Question

I'm developing an app that will support multiple languages and I'm looking for the best way to set the different languages.

The app works with a UINavigationController. In the first ViewController you can select the language pressing a UIButton and then in the following view controllers the labels' texts would be changed to the corresponding language.

The way I'm doing it right now is by changing the value of a BOOL property when I create the instance of the new ViewController depending on the UIButton sender tag.

FirstViewController.m

-(void)goToSecondVC{

    SecondViewController *secondVC = [[SecondViewController alloc]init];

    if ([sender tag] == 1) {
        secondVC.english = YES;
    }else{
        secondVC.english = NO;
    }


    [self.navigationController pushViewController:startScreenVC];

}

SecondViewController.m

-(void)viewWillAppear:(BOOL)animated{

    if(self.english){
        self.myLabel.text = @"This text will be in English";
    }else{
        self.myLabel.text = @"This text will be in Spanish";
}

I know this is probably not the best way to achieve this task. What would you recommend, notifications, delegation, singletons? I'm looking for a kind of global variable that could be written and read from every ViewController

Was it helpful?

Solution 2

The implementation is straightforward and correct.

Since you want to have this information known to every view controller, a better approach is to use KVO and a store for the language info value.

For example, save it to NSUserDefaults. Then from any view controller your could access it.

Then if some view controller wants to get notification when this value gets changed, it could observe the NSUserDefaults object for that value. (with Storyboard, you could use a Shared User Defaults Controller).

OTHER TIPS

You should be using localization for this.

You can get the language like this:
NSString *language = [[NSLocale currentLocale] objectForKey: NSLocaleLanguageCode];
Take a look at this this tutorial for localization: http://www.raywenderlich.com/2876/localization-tutorial-for-ios
or this SO ansawer

If you want to access the current language setting from any place in your app its worth taking a look at the Singleton design pattern. Here's an excellent summary.

You can also use the [NSUserDefaults standardUserDefaults] which is a predefined Singleton object or simply create your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top