How to use UIKit localized string in my app

会有一股神秘感。 提交于 2019-12-04 10:58:54

问题


We are building a iOS game, our company requires cancel button in a UIAlertView should always be localized depend on user's device language.

It looks like there is such a string in UIKit framework, how can I access it in my own app?

Or, any other way to create a UIAlertView with a localized cancel button?

Thank you

Answer by myself:

Problem solved by the following code:

NSBundle* uikitBundle = [NSBundle bundleForClass:[UIButton class]];
NSString *language = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];
NSBundle *languageBundle = [NSBundle bundleWithPath:[uikitBundle pathForResource:language ofType:@"lproj"]];
NSLog(@"%@: %@", language, NSLocalizedStringFromTableInBundle(@"Cancel", @"Localizable", languageBundle, nil));

This read string files from /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/UIKit.framework

Following languages have different name between NSUserDefault and UIKit.framework folder: fr en zh-Hans it de ja nl es pt-PT nb zh-Hant en-GB. They should be handled by code.


回答1:


Easy method for Strings already in UIKit

NSBundle* uikitBundle = [NSBundle bundleForClass:[UIButton class]];
NSString *cancel = [uikitBundle localizedStringForKey:@"Cancel" value:nil table:nil];



回答2:


Swift 4:

    let bundle = Bundle.init(for: UIButton.self)
    let doneTitle = bundle.localizedString(forKey: "Done", value: nil, table: nil)
    for state: UIControlState in [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved] {
        buttonDone.setTitle(doneTitle, for: state)
    }



回答3:


You should be using NSLocalizedString from foundation framework: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html

There is a nice tutorial about it: http://www.icanlocalize.com/site/tutorials/iphone-applications-localization-guide/

Those predefined button names will be translated automatically by OS (Done in tab bar) and in uialertview you can set Cancel button title to be whatever you want...

     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"title",@"titleKey") 
message:NSLocalizedString(@"message",@"messageKey") 
delegate:self 
cancelButtonTitle:NSLocalizedString(@"cancel",@"cancelKey") 
otherButtonTitles:nil];


来源:https://stackoverflow.com/questions/6909885/how-to-use-uikit-localized-string-in-my-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!