11

특성 문자열이있는 UILabel이 있습니다.번역 된 문자열 변환

enter image description here

지금, 나는이 영어와 이탈리아어로 문자열을 기인 번역 할 필요가 : 여기의 PRINTSCREEN이다. 나는 이것을 할 방법을 찾고있다. 이 속성 문자열을 코드별로 부분별로 작성할 수 있습니까? 나는 전체 문자열이 설정된 다음 범위별로 속성을 설정하는 해결책을 찾았습니다. 그러나 문자열을 번역 할 때 단어가 더 길거나 작기 때문에 더 이상 범위를 알 수 없습니다.

+0

NSAttributedString 메소드'enumerateAttributesInRange : options : usingBlock :'을 사용해보십시오. 이렇게하면 범위와 함께 각 속성이 반환됩니다. 해당 범위 부분의 문자열을 부분별로 추출하여 번역 할 수 있습니다. – ZeMoon

답변

6

또 다른 옵션은 NSAttributedStrings을 만들 수있는 .RTF 지역화 파일을 만드는 것입니다 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]; 
    } 
} 

방법

나중에 다음과 같이 사용될 수있다 :

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

attrStr@"Press <b>Next</b> button to ..." 될 수있다.

0

문자열의 개별 부분을 번역하여이 문제를 해결할 것입니다. 속성이 지정된 문자열은 실제로 네 개의 문자열을 연결 한 버전이기 때문에이 경우에도 작동합니다.

하지만 숫자를 사용하는 형식을 저장해야합니다. 일부 언어에서는 텍스트가 "3   Erweiterung"일 수 있습니다. NSLocalizedStringWithDefaultValue을 사용하여이 작업을 수행 할 수 있습니다.

NSString *stepFormat = NSLocalizedStringWithDefaultValue(@"AttributedStringStepFormat", @"main", [NSBundle mainBundle], @"Step %ld", @"'Step 4' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft'"); 
NSString *step = [NSString stringWithFormat:stepFormat, (long)4]; 

NSString *erweiterungFormat = NSLocalizedStringWithDefaultValue(@"AttributedStringErweiterungFormat", @"main", [NSBundle mainBundle], @"Erweiterung %ld", @"'Erweiterung 3' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft'"); 
NSString *erweiterung = [NSString stringWithFormat:erweiterungFormat, (long)3]; 

NSString *erhalten = NSLocalizedStringWithDefaultValue(@"AttributedStringErhalten", @"main", [NSBundle mainBundle], @"erhalten", @"'erhalten' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft'"); 
NSString *dauerhaft = NSLocalizedStringWithDefaultValue(@"AttributedStringDauerhaft", @"main", [NSBundle mainBundle], @"dauerhaft", @"'dauerhaft' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft'"); 

NSString *result = [NSString stringWithFormat:@"%@ - %@ - %@\n%@", step, erweiterung, erhalten, dauerhaft]; 

NSRange stepRange = [result rangeOfString:step]; 
NSRange erweiterungRange = [result rangeOfString:erweiterung]; 
NSRange erhaltenRange = [result rangeOfString:erhalten]; 
NSRange dauerhaftRange = [result rangeOfString:dauerhaft]; 

// Create attributed string 

당신이 좋은 문자열을 얻을이 방법은 번역하는 데 사용할 수있는 파일 :이 방법 같은

/* 'dauerhaft' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft' */ 
"AttributedStringDauerhaft" = "dauerhaft"; 

/* 'erhalten' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft' */ 
"AttributedStringErhalten" = "erhalten"; 

/* 'Erweiterung 3' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft' */ 
"AttributedStringErweiterungFormat" = "Erweiterung %ld"; 

/* 'Step 4' in 'Step 4 - Erweiterung 3 - erhalten\ndauerhaft' */ 
"AttributedStringStepFormat" = "Step %ld"; 
+0

나는 이것이 아랍어로는 효과가 있다고 생각하지 않는다. – OlivaresF

+1

현지화는 아랍어에 어떤 효과가 있습니까? :) – Lope

+1

@Lope 당신이 그것을하는 방법을 안다면, 모든 것이 현지화와 함께 작동합니다. :) 초보자 용 : https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/SupportingRight-To-LeftLanguages/SupportingRight-To-LeftLanguages.html – Manuel

2

뭔가 일할 수 있습니다. NSAttributedString을 사용하여 속성을 기반으로 파트를 추출하고 각 파트를 변환하고 동일한 속성을 적용한 다음 최종 변환 된 특성 문자열을 반환합니다. (일부 응용 프로그램의 설정에 특정 글꼴 예를 들면 세트 색)

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

동적 서식을 사용하려면, 내가 사용하고 있습니다 :

-(NSAttributedString*)translateAttribString:(NSAttributedString*)attribString toLanguage:(NSString*)language 
{ 
    NSMutableAttributedString *returnString = [[NSMutableAttributedString alloc]init]; 

    NSRange totalRange = NSMakeRange (0, attribString.length); 

    [attribString enumerateAttributesInRange: totalRange options: 0 usingBlock: ^(NSDictionary *attributes, NSRange range, BOOL *stop) 
    { 
     NSLog (@"range: %@ attributes: %@", NSStringFromRange(range), attributes); 

     NSString *string = [[attribString string] substringWithRange:range]; 

     NSLog(@"string at range %@", string); 

     //Translate 'string' based on 'language' here. 

     NSString *trans; //This will hold the translated string. 

     NSAttributedString *translatedString = [[NSAttributedString alloc]initWithString:trans attributes:attributes]; 

     [returnString appendAttributedString:translatedString]; 

    }]; 

    return returnString; 
} 
0

나는 일반적으로 강조 표시된 부분을 별도로 번역하고 찾기 쉽고 대체하기 쉬운 고유 한 자리 표시자를 원본 텍스트에 추가합니다. 위한

예 "이 단어 굵게"localized.strings에서

그것은
가 "BaseText"= "이 -Word- 굵게"것;
"HighlightedText"= "word";

이제 우리는 "BaseText"키를 사용하여 원래 문자열을 할 수 있습니다 :
1. "HighlightedText"키와 지역화 된 문자열로 교체 "-Word-"문자열
2의 범위를 찾습니다.
3. 원래 자리 표시 자 범위, 원래 자리 표시 자 길이 및 번역 길이를 사용하면 새 범위를 쉽게 계산하고 특정 범위를 적용 할 수 있습니다.

이 접근법은 연결보다 유연하며 번역의 단어 순서에 의존하지 않습니다.

그것을 위해 확장입니다 : 필요한 경우

extension NSMutableAttributedString { 
    func replacePlaceholder(_ placeholder: String, with translation: String, attributes: [String: Any]) { 

     // find the placeholder 
     var range = (string as NSString).range(of: placeholder) 

     // nothing to replace 
     if range.location == NSNotFound { 
      return 
     } 

     // replace it with the translation 
     mutableString.replaceCharacters(in: range, with: translation) 

     // adjust range according to changes 
     range.length = range.length + translation.length - placeholder.length 

     // apply attributes 
     self.setAttributes(attributes, range: range) 
    } 
} 

당신은 몇 자리를 잇달아 교체 할 수 있습니다.