Changing language on the fly, in running iOS, programmatically

后端 未结 7 997
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 22:45

I\'ve been stackling and googling for hours. And I\'m kind of desperate now. I would like to change the language of my application inside the app not only with the default l

7条回答
  •  攒了一身酷
    2020-11-29 23:11

    yes, i had the same problem, then i managed it with my own language setting in my prefFile, where i set a variable for the language setting:

    // write a new value in file and set the var
    - (void)changeLangInPrefFile:(NSString *)newLanguage {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myPreference.plist"];
        NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
        //here add elements to data file and write data to file
        [data setObject:newLanguage forKey:@"language"];
        [data writeToFile:path atomically:YES];
        [data release];
    
    // NSString *chosenLang; <- declared in .h file
        if (chosenLang != nil){
            [chosenLang release];
            chosenLang = nil;
        }
        chosenLang = [[NSString alloc] initWithString:(@"%@",newLanguage)];
    
    }
    
    // read the language from file and set the var:
    - (void)readFromFileInBundleDocuments {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myPreference.plist"];
        NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    
        NSString *chosenLangTemp = [savedStock objectForKey:@"language"];
        NSLog (@"read in file: %@", chosenLangTemp);
        if (chosenLang != nil){
            [chosenLang release];
            chosenLang = nil;
        }
        chosenLang = [[NSString alloc] initWithString:(@"%@",chosenLangTemp)];
        [savedStock release];
    }
    

    then i load all the contents from different files depending on the language for example i can load "an_image_eng.png" or "an_image_ita.png", or have 2 different .xib file and for the text to load i use different dictionary-files, one for each language, with all words/expressions translated, i just load the chosen one and read in it the right expression for every text to be load (the code to load it is similar to the method i wrote in this example, you can just arrange it to read the right word for every expression: just look at the value for objectForKey in the right dictionary file, where objectForKey is the word to translate and its value is the word translated)...

提交回复
热议问题