Localizing Dynamic Plural Noun messages (e.g. “5 Items Processed”) on iPhone using Objective-C

后端 未结 4 1093
故里飘歌
故里飘歌 2020-12-22 23:50

In my current app, I have code that displays a message, e.g. \"5 Items Processed.\" To keep the phrase grammatically correct, i.e. whether or not it should be \"5 Item\" or

4条回答
  •  抹茶落季
    2020-12-23 00:46

    As of iOS 7, Foundation framework has native support for pluralization. Here is a quick tutorial how to use it:

    Create a plist file named as Localizable.stringsdict

    English Localization:

    
    
    
        
            %d tasks waiting for action
            
                NSStringLocalizedFormatKey
                %#@tasks@ waiting for action
                tasks
                
                    NSStringFormatSpecTypeKey
                    NSStringPluralRuleType
                    NSStringFormatValueTypeKey
                    d
                    one
                    A task is
                    two
                    Two tasks are
                    other
                    %d tasks are
                
            
        
    
    

    Polish Localization:

    
    
    
        
            %d tasks waiting for action
            
                NSStringLocalizedFormatKey
                Masz %#@zadanie@ do zrobienia
                zadanie
                
                    NSStringFormatSpecTypeKey
                    NSStringPluralRuleType
                    NSStringFormatValueTypeKey
                    d
                    one
                    jedno zadanie
                    few
                    %d zadania
                    other
                    %d zadań
                
            
        
    
    

    And finally in your implementation file, you can call the dictionary like this:

    cell.tasksInfoLabel.text = [NSString localizedStringWithFormat:NSLocalizedString(@"%d tasks waiting for action", @"%d tasks waiting for action"), (long)taskCount];
    

    EDIT: Thanks Zaphod for pointing this out ->: You also need to create the Localizable.strings file alongside the .stringsdict to have the pluralization work (even if it's empty).

提交回复
热议问题