How to use NSLocalizedString in IB [iPhone SDK]?

前端 未结 5 1797
误落风尘
误落风尘 2021-02-03 13:55

When I assign text programmatically, I can use NSLocalizedString(....), but if I am writing the text directly in IB (say to a UILabel) how do I localize it?

5条回答
  •  执念已碎
    2021-02-03 14:48

    I also was searching for a solution, not necessarily for iPhone, but XCode/IB in general. All references did not deal with the fact that you might need a key internally to indicate a state and want to display a localized string for the user in a label or text cell corresponding to that key. I did not found in first step a standard approach how to store e.g. a key value for a key in shared user defaults and display the localized string for that key value in a label.

    I found a solution wich does not need many coding and is compliant with the bindings in ib.

    First you provide a file Localizable.strings e.g. with a line containing

    "MyKeyValue" = "Localized display label";
    

    Now you can localize the key value with: NSLocalizedString(aKeyValue,nil).

    In the label you did not find any value transformer dealing with NSLocalized String. So I created a class KeyToLocalizedStringTransformer to transform a key value into a localized string:

    @interface KeyToLocalizedStringTransformer : NSValueTransformer {}
    
    @implementation KeyToLocalizedStringTransformer
    
    + (Class)transformedValueClass
    {
        return [NSString class];
    }
    
    + (BOOL)allowsReverseTransformation
    {
        return NO;
    }
    
    - (id)transformedValue:(id)aValue
    {
        NSString *NLString = [NSString stringWithString:NSLocalizedString(aValue,nil)];
    return NLString;
    }
    

    Last step for preparing is to register the transformer e.g. in +initialize:

    NSValueTransformer *transformer = [[KeyToLocalizedStringTransformer alloc] init];
    [NSValueTransformer setValueTransformer:transformer forName:@"KeyToLocalizedStringTransformer"];   
    

    Now you can use a value transformer in the bindings for the text field or cell (Simply type in the name if you do see only the NSUnArchiveFromData and so on...)

    Sorry no image here from IB 'cause I am new here and "have no reputation": you have to imagine the binding to the shared user defaults controller, Kontroller key: values, Model Key Path: MyStateKey and a value transformer as described.

    As a result you dont have to do anything in the nl duplicated nib with the label, simply translate the string in the Localizable.strings.

提交回复
热议问题