Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UIKit localized string in my app

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.

like image 712
Zhao Xiang Avatar asked Aug 02 '11 09:08

Zhao Xiang


People also ask

How do I use localized strings in SwiftUI?

Use it in custom SwiftUI views to make them ready for localization. Enable the "Use Compiler to Extract Swift Strings" build setting to extract LocalizedStringKeys from code when exporting for localization in Xcode. Format your strings to internationalize your code, and style them with Markdown.

How do I localize my iOS app?

Select your root project file, and then proceed to the project panel. Find the Localization section section, click the “plus” (+) icon, and add the desired languages. Select only the Localizable. strings file for localization.

What is a Localised string?

A localized string can have different values depending on the language in which the project is being build. There are two categories of localized strings: the strings included in the installation package's UI, common to every MSI file.

What is localized string key?

The key used to look up an entry in a strings file or strings dictionary file.


2 Answers

Easy method for Strings already in UIKit

NSBundle* uikitBundle = [NSBundle bundleForClass:[UIButton class]];
NSString *cancel = [uikitBundle localizedStringForKey:@"Cancel" value:nil table:nil];
like image 104
Daniel Broad Avatar answered Oct 21 '22 04:10

Daniel Broad


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)
    }
like image 42
Dmitry Avatar answered Oct 21 '22 04:10

Dmitry