Ben*_*ual 12 xcode localization nsattributedstring nslocalizedstring ios
我有一个带有属性字符串的UILabel.这是它的打印屏幕:

现在,我必须将这个属性字符串翻译成英语和意大利语.我正在寻找一种方法来做到这一点.我可以逐个代码地在代码中构建这个属性字符串吗?我只找到了一个解决方案,其中设置了整个字符串,然后通过范围设置属性.但是当我翻译字符串时,我不再知道范围,因为这些字词更长或更小.
另一种选择是创建本地化的.rtf文件,从中创建NSAttributedStrings:
NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
Run Code Online (Sandbox Code Playgroud)
要使用动态格式化(例如设置颜色,特定于某些应用程序设置的字体),我正在使用一些类似html的格式,使用1-char标签,然后我在应用程序内部应用格式.
// NSMutableAttributedString category method
/**
* Updates the attributes of xml elements (where the xml tags are formed of 1 single char) with the passed attributes from param `tagsAttributes`
* Current version doesn't support recursive tags (tags in tags)
* All tags of form '<char>' or '</char>' will be used as formatting (the resulting string should not be expected to have any tags of this form)
* @param tagsAttributes - list of attribute dictionaries, where the key is the tag name */
-(void)formatCharXMLTagsUsingAttributes:(NSDictionary *)tagsAttributes {
int strippedLength = 0;
NSString *str = [[self string] copy];
NSScanner *scanner = [NSScanner scannerWithString:str];
while (![scanner isAtEnd]) {
NSString *tag = nil;
do {
[scanner scanUpToString:@"<" intoString:nil];
[scanner scanString:@"<" intoString:nil];
if (scanner.scanLocation + 2 < [str length] && [str characterAtIndex:scanner.scanLocation + 1] == '>') {
[scanner scanUpToString:@">" intoString:&tag];
[scanner scanString:@">" intoString:nil];
}
} while (!tag && ![scanner isAtEnd]);
if ([scanner isAtEnd]) {
break;
}
NSString *endTag = [NSString stringWithFormat:@"</%@>", tag];
NSString *tmpString;
[scanner scanUpToString:endTag intoString:&tmpString];
[scanner scanString:endTag intoString:nil];
NSRange range;
strippedLength += 7; // start tag + end tag length
range.location = scanner.scanLocation - [tmpString length] - strippedLength;
range.length = [tmpString length] + 7;
[self replaceCharactersInRange:range withString:tmpString];
range.length -= 7;
[self addAttributes:tagsAttributes[tag] range:range];
}
}
Run Code Online (Sandbox Code Playgroud)
之后可以像这样使用该方法:
NSDictionary* highlightAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName: [UIFont boldSystemFontOfSize:16]};
NSDictionary *xmlTagsAttributes = @{@"b": highlightAttributes};
[attrStr formatCharXMLTagsUsingAttributes:xmlTagsAttributes];
Run Code Online (Sandbox Code Playgroud)
哪里attrStr可能@"Press <b>Next</b> button to ...".
| 归档时间: |
|
| 查看次数: |
6685 次 |
| 最近记录: |