美文网首页iOS ProcessiOS开发CVTE_iOS
Storyboard多语言‘另类’实现

Storyboard多语言‘另类’实现

作者: SeeLee | 来源:发表于2014-12-30 17:46 被阅读1895次

    作者:linyanqun,CVTE iOS开发工程师

    Storyboard本地化虽然Xcode有自带方法,但由于每次生成strings文件时,会把已经翻译的字符串和未翻译的字符串相互混在一起,给翻译人员或开发人员增加整理繁琐工作。还有另外一种实现方式则是通过将包含文本的控件通过拖线到ViewController,再然后代码NSLocalizedString进行多语言化,但这会给ViewController添加大量冗余属性或变量。

    那么,除了以上两种方式。便有第三种试被提出来,即在文本按钮加载时,通知重载其awakeFromNib,然后再使用NSLocalizedString(self.text, nil);但是这又会导致脚本不能导致strings列表。那么,既然系统不能导出strings列表,我们自己是否可以写脚本来实现呢?

    本文主要就是来谈,怎么从storyboard和xib文件中导出strings列表。(由于最终实现方案是开发一个Xode插件,本文重点谈objc生成strings方案)

    首先需要明确我一个需求:strings列表需要是之后新增了,即不重复之前的strings列表。

    Storyboard可以设置文本的控件有:

    1. UIButton
    2. UILabel
    3. UINavigationItem //主要出现在ViewController控件中
    4. UIBarButtonItem

    Storyboard和xib其实是一个标准的xml文档,通过查看它们的源代码,确定了上述控件在xml出现的节对应形式

    //UIButton
    <button><state  title="文本"></state></button>
    
    //UILabel
    <label text="文本"></label>
    
    //UINavigationItem
    <navigationItem title="文本"></navigationItem>
    
    //UIBarButtonItem
    <barButtonItem title="文本"></barButtonItem>
    
    

    OK,确定了以上控件对应节点后,就可以写出对应的xPath了。

    NSString *xPath = @"//button[@title] | //navigationItem[@title] | //barButtonItem[@title] | //label[@text]"
    
    

    将storyboard、xib转换成xmlDoc对象非常简单,只需要知道文件的路径url(NSURL)。

    NSXMLDocument *doc = [[NSXMLDocument alloc]initWithContentsOfURL:url options:kNilOptions error:nil];
    

    有了xml doc就可以轻松的拿到包含文本控件对应的元素节点了

    NSArray *nodes = [doc nodesForXPath:xPath error:nil];
    

    声明一个数组strings来存储文本,通过遍历结果节点来获取对应的文本

    NSMutableArray *strings = [NSMutableArray array];
    
    for(NSXMLElement *element in nodes)
    {
        //label和文本属性名为text
        NSString *atrributeName = [element.name isEqualToString:@"label"] ? @"text" : @"title";
    
        //获取属性元素
        NSXMLNode *node = [element attributeForName:atrributeName];
    
        if(node  && node.stringValue.length)
        {
            if(![strings containsObject:node.stringValue])
            {
                [strings addObject:node.stringValue];
            }
        }
    }
    

    为了避免重复生成已经出现(翻译),可以通过加载项目基Localizable.strings来过滤掉重复的文本;一般基语言都是en(英文)。

    NSString *localizabelPath = [project stringByAppendingPathComponent:@"en.lproj/Localizable.strings"];
                localizedTable = [NSDictionary dictionaryWithContentsOfFile:localizabelPath];
    
    if(localizedTable)
    {
        NSUInteger idx = 0;
        while (idx < strings.count)
        {
            if(localizedTable[strings[idx]])
            {
                [strings removeObjectAtIndex:idx];
                continue;
            }
            idx++;
        }
    }
    

    到了这里,数组strings的元素就是新添加控件的需要本地化的文本了。现在需要做是将strings转换成Localizable.strings文件格式的字符串了。

    NSMutableString *result = [NSMutableString string];
    for(NSString *str in strings)
    {
        //需要注意:.strings的双引号需要通过转义
        NSString *text = [str stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        [result appendFormat:@"\"%@\" = \"%@\";\n\n", text, text];
    }
    

    最后将result追加到en.lproj/Localizable.strings 文件中,当然,如果项目不存在该文件,则创建一个。

    if(localizabelPath.length)
    {
        NSFileHandle *handler = [NSFileHandle fileHandleForWritingAtPath:localizabelPath];
        //多加四个空格,区分之前版本的文件
        [result insertString:@"\n\n\n\n" atIndex:0];
        [handler seekToEndOfFile];
        [handler writeData:[result dataUsingEncoding:NSUTF8StringEncoding]];
    }
    else
    {
        localizabelPath = [project stringByAppendingPathComponent:@"en.lproj/Localizable.strings"];
        [fileManager createDirectoryAtPath:localizabelPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:NULL];
        [result writeToFile:localizabelPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    }
    

    OK,一个项目的storyboard/xib多语言文本就这样轻而易举地导出到Localizable.strings文件了。以下把上述代码再合并一下,想看效果?直接复制代码运行一下吧。其实项目的路径需要自己改下哦!

    /**
     *  自动生成指定项目Storyboard本地化文本列表
     *
     *  @param path 项目所在的路径
     */
    - (void)storyboardAutoLocalizableWithPath:(NSString *)path
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        NSMutableArray *strings    = [NSMutableArray array];
        //原来本地化的文本
        NSDictionary *localizable  = nil;
        //本地化路径
        NSString *localizabelPath  = nil;
    
        for(NSString *file in [fileManager subpathsAtPath:path])
        {
            if([file hasSuffix:@".storyboard"] ||[file hasSuffix:@".xib"])
            {
                NSURL *url         = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:file]];
                //解析xml
                NSXMLDocument *doc = [[NSXMLDocument alloc]initWithContentsOfURL:url options:kNilOptions error:nil];
    
                if(!doc)
                {
                    continue;
                }
    
                NSArray *nodes = [doc nodesForXPath:@"//label[@text] | //button/state[@title] | //navigationItem[@title] | //barButtonItem[@title]" error:nil];
                
                for(NSXMLElement *element in nodes)
                {
                    //label和文本属性名为text
                    NSString *atrributeName = [element.name isEqualToString:@"label"] ? @"text" : @"title";
    
                    //获取属性元素
                    NSXMLNode *node = [element attributeForName:atrributeName];
    
                    if(node  && node.stringValue.length)
                    {
                        if(![strings containsObject:node.stringValue])
                        {
                            [strings addObject:node.stringValue];
                        }
                    }
                }
            }
            //获取基语言本地化文件
            else if([file hasSuffix:@"en.lproj/Localizable.strings"])
            {
                localizabelPath = [path stringByAppendingPathComponent:file];
                localizable = [NSDictionary dictionaryWithContentsOfFile:localizabelPath];
            }
        }
       
        if(localizable)
        {
            NSUInteger idx = 0;
            while (idx < strings.count)
            {
                if(localizable[strings[idx]])
                {
                    [strings removeObjectAtIndex:idx];
                    continue;
                }
                idx++;
            }
        }
        
        if(!strings.count)
        {
            return;
        }
    
        //文本排序
        [strings sortUsingSelector:@selector(compare:)];
    
        NSMutableString *result = [NSMutableString string];
    
        for(NSString *str in strings)
        {
            NSString *text = [str stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
            [result appendFormat:@"\"%@\" = \"%@\";\n\n", text, text];
        }
    
        if(localizabelPath.length)
        {
            NSFileHandle *handler = [NSFileHandle fileHandleForWritingAtPath:localizabelPath];
            [result insertString:@"\n\n\n\n" atIndex:0];
            [handler seekToEndOfFile];
            [handler writeData:[result dataUsingEncoding:NSUTF8StringEncoding]];
        }
        else
        {
            localizabelPath = [path stringByAppendingPathComponent:@"en.lproj/Localizable.strings"];
            [fileManager createDirectoryAtPath:localizabelPath
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:NULL];
    
            [result writeToFile:localizabelPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
        }
    }
    

    本文先介绍了怎么提取Storyboard的多语言文本,后续篇幅将介绍如何将上述的方法应用到实际开发项目中,并且会介绍如何将方法以插件的形式集成到Xcode中。敬请期待!

    相关文章

      网友评论

      • SeeLee:@Kafka0806 百度一下markdown就行了,显示代码非常简单,如果要在简书上使用markdown来写文章需要到设置里面去设置为使用markdown,默认它是用富文本编辑器,markdown语法显示代码如下:

        ```
        your code
        ```
      • SeeLee:@Kafka0806 是MarkDown语法,简书的支持还不是太好,要不然会有关键字高亮

      本文标题:Storyboard多语言‘另类’实现

      本文链接:https://www.haomeiwen.com/subject/jkkztttx.html