gpt4 book ai didi

ios - 翻译属性字符串

转载 作者:技术小花猫 更新时间:2023-10-29 10:37:09 28 4
gpt4 key购买 nike

我有一个带有属性字符串的 UILabel。这是它的打印屏幕:

enter image description here

现在,我必须将这个属性字符串翻译成英语和意大利语。我正在寻找一种方法来做到这一点。我可以在代码中逐个构建这个属性字符串吗?我只找到了一个解决方案,其中设置了整个字符串,然后按范围设置了属性。但是当我翻译字符串时,我不知道范围了,因为单词更长或更小。

最佳答案

另一种选择是创建本地化的 .rtf 文件,从中创建 NSAttributedStrings :

NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];

要使用动态格式(例如,设置颜色、特定于某些应用程序设置的字体),我使用了一些类似 html 的格式,带有 1 个字符的标签,之后我从应用程序内部应用格式。

// 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];
}
}

该方法之后可以这样使用:

NSDictionary* highlightAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName: [UIFont boldSystemFontOfSize:16]};
NSDictionary *xmlTagsAttributes = @{@"b": highlightAttributes};
[attrStr formatCharXMLTagsUsingAttributes:xmlTagsAttributes];

在哪里attrStr可能是 @"Press <b>Next</b> button to ..." .

关于ios - 翻译属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854922/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com